Uploading file to controller using typescript

12,594

TransformRequest function: This makes your request to be sent as a FormData instead as a JSon object.

 formDataObject(data: any): any {
        var fd = new FormData();
        angular.forEach(data, function (value, key) {
            fd.append(key, value);
        });
        return fd;
    }

In your angular resource, define the save options and pass the transformRequest function you created earlier.

uploadChequeFile(): ng.resource.IResourceClass<IChequeLoanResource> {
        return this.$resource<IChequeLoanResource>("/Cheque/UploadChequeImage", null,
            {
                save: {
                    method: "POST",
                    transformRequest: this.formDataObject,
                    headers: { 'Content-Type': undefined, enctype: 'multipart/form-data' }
                }
            });
    }

In your controller, just call your save method from the resource passing your file.

var chequeFilePathInput: any = $("#chequeFilePath");
        if (chequeFilePathInput[0].files) {
            var resource: ng.resource.IResourceClass<services.IChequeLoanResource> = this.uLendService.uploadChequeFile();
            resource.save({ "files": chequeFilePathInput[0].files[0] }, (result: any) => {
                if (!result || !result.success) {
                    this.errorMessage = "Error al subir la imagen al servidor. Por favor contáctanos si el error persiste.";
                } else {
                    this.chequeLoan.cheque.filePath = result.message;
                    this.saveChequeLoan();
                }
            });
        } else {
            this.errorMessage = "La imagen del cheque es requerida.";
        }

Finally, your controller must receive the IList parameters (with the same name defined in your angular controller)

public JsonResult UploadChequeImage(IList<IFormFile> files)
    {
        try
        {
            if (files != null && files.Count > 0)
            {
                return CreateResponse(true, CreateFile(files[0], @"img\cheques"));
            }
Share:
12,594
gmesorio
Author by

gmesorio

Updated on June 25, 2022

Comments

  • gmesorio
    gmesorio almost 2 years

    I am using ASP.NET MVC 5 for the back-end and Angular + Typescript for the front-end of a web application.

    I am trying to upload a file to the server, but for some reason the controller is not getting the file as parameter (the parameter in the controller is null).

    I'm sharing below code.

    Thanks in advance!

    HTML:

    <input id="filePath" name="filePath" type="file" accept="image/*" />
    <a id="uploadImage" ng-click="ctrl.uploadFile()">Upload</a>
    

    Typescript:

    // controller class:
    uploadFile(): void {
        var filePathInput: any = $("#filePath");
        if (filePathInput[0].files) {
            var file: any = filePathInput[0].files[0];
            var resource: any = this.service.uploadFile();
            resource.save(file, (result: any) => {
                if (!result || !result.success) {
                    alert("error");
                } else {
                    alert("ok");
                }
            });
        }
    }
    
    // service class:
    uploadFile(): ng.resource.IResourceClass<IMyResource> {
        return this.$resource("/MyController/UploadImage", null, { method: "POST" });
    }
    

    Backend Controller:

    [HttpPost]
    public JsonResult UploadImage([FromBody]HttpPostedFileBase file)
    {
        if (file == null || file.ContentLength == 0)
        {
            return NullParameterResponse();
        }
        else
        {
            file.SaveAs("/img/" + Path.GetFileName(file.FileName));
            return SuccessResponse();
        }
    }