0

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 Answer 1

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:

enter image description here

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.