使用typescript将文件上传到控制器

使用typescript将文件上传到控制器

本文介绍了使用typescript将文件上传到控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 ASP.NET MVC 5 作为后端, Angular + Typescript 作为Web应用程序的前端。

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).

我正在分享以下代码。

提前致谢!

HTML :

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

打字稿:

// 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" });
}

后端控制器:

[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();
    }
}


推荐答案

TransformRequest function:这使您的请求作为FormData发送,而不是作为JSon对象发送。

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;
    }

在角度资源中,定义保存选项并传递您创建的transformRequest函数早期。

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' }
                }
            });
    }

在你的控制器中,只需从传递文件的资源中调用你的save方法。

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.";
        }

最后,您的控制器必须接收IList参数(在你的角度控制器)

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"));
            }

这篇关于使用typescript将文件上传到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 19:22