4

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();
    }
}
2
  • 1
    The first thing I noticed is the different URL segment: UploadImage -> UploadChequeImage Commented Jul 24, 2016 at 2:35
  • Sorry, that's my mistake when I posted the question. This was because I tried to simplify the problem in the question by renaming the methods, but I didn't see that one. I just edited the question to fix that. The controller method is in fact called by the front-end, but the parameter (file) is always null. Commented Jul 24, 2016 at 12:07

1 Answer 1

2

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"));
            }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.