【问题标题】:File upload with ASP.NET Core + VueJS使用 ASP.NET Core + VueJS 上传文件
【发布时间】:2020-03-07 04:20:12
【问题描述】:

我有 ASP.NET 核心,VueJS 应用程序。
任务是上传带有表单数据的文件
问题:表单数据为空

这是我拥有的 HTML 和 JS 类。它使用 Jquery Ajax 调用来上传模型数据 + 文件。 我无法将第三个库用作 Axios(至少我不知道如何),而是纯 Jquery。

有没有人建议这如何工作?

HTML

<form method = "post" enctype = "multipart/form-data" role = "form" v - on: submit.prevent >
  <div id = "formEditInner" >
     ...
      <div class = "form-group" >
          <label class = "control-label" for  = "photo" > Photo </label >
          <span class = "required" aria - required = "true" >  *  </span >
          <input name = "photo" type = "file" class = "form-control" v - on: change = "addPhoto" placeholder = "Upload photo" >
       </div>
     ...
   </div>
</form >

JS

class ApiClient {

    constructor(url, xhrFields) {
        this._url = url;
        this._xhrFields = xhrFields || { withCredentials: false };
    }


    //THIS METHOD IS IMPORTANT
    _upload(method, url, data, isJson) {
        url = this._url + '/' + url.replace('.', '/');
        if (data && typeof data !== 'object') {
          url += '/' + data;
          data = null;
        }
        let request = { url: url, data: data, type: method, xhrFields: this._xhrFields, crossDomain: true };

        //request.contentType = "multipart/form-data";
        request.contentType = false;  
        request.processData = false;

        return new Promise((res, rej) => {
          request.success = res;
          request.error = rej;
          $.ajax(request);
        });
     }

     uploadAsync(url, data) {
         return this._upload('POST', url, data, false);
     }
 }

服务器代码没问题,除了我收到的参数值为NULL

[AllowAnonymous]
[HttpPost("upload")]
public async Task<bool> Upload(  IList<IFormFile> photo, string zipCode )
{

     return  (photo != null);
}

【问题讨论】:

    标签: jquery vue.js asp.net-core file-upload asp.net-ajax


    【解决方案1】:

    您可以创建FormData 并动态附加字段。例如,

    addPhoto(e){
        var formData = new FormData();
        // field: photo
        for(var i=0; i< e.target.files.length; i++){
            formData.append("photo",e.target.files[i]);
        }
        // field: zipCode
        formData.append("zipCode", '123456');
    
        // now you can invoke the ApiClient as below : e.g.
        // ... var api = new ApiClient("https://localhost:5001");
        return api.uploadAsync("upload", formData)
            .then(
                r => console.log(r)   // success
            );
    },
    

    演示:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-03
      • 1970-01-01
      • 2021-08-02
      • 2017-08-03
      • 1970-01-01
      • 1970-01-01
      • 2019-02-23
      • 1970-01-01
      相关资源
      最近更新 更多