File upload with ASP.NET Core + VueJS

你。 提交于 2021-01-29 10:53:43

问题


I have ASP.NET core , VueJS app.
The task is to Upload file with form data
Problem: Form data is null

Here is the HTML and JS class I have. Its using Jquery Ajax call to upload model data + file. I am unable to use 3rd libraries as Axios (at least I dont know how) , but pure Jquery.

Does anybody have suggestion how this can work ?

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

Sever code is fine, except the parameter values I receive are NULL

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

     return  (photo != null);
}

回答1:


You can create a FormData and append the fields dynamically. For example,

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

Demo:



来源:https://stackoverflow.com/questions/58802040/file-upload-with-asp-net-core-vuejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!