Search code examples
node.jsvue.jsmultipartform-datamulteraxios

how to submit "multipart/form-data" from VueJs


I am using VueJs / axios in frontend and multer in nodejs for a simple file upload to work.

So far all tries has been unsuccessful. While this can be achieved in 100 ways in angular 1/2 using ng-upload and other similar plugins. But VueJs seems to be lacking this basic functionality. Based on my research axios doesnt support "multipart/form-data". Ref https://github.com/mzabriskie/axios/issues/789 .

multer and other nodejs libraries seems to work with "multipart/form-data" seamlessly from angular 1/2. However same functionality is not working from VueJs.

Is there any other alternative other than axios which support "multipart/form-data" aka -- WebKitFormBoundary ??

Many Thanks


Solution

  • I found two ways of achieving this in VueJs. There might be more.

    Option 1. Using Axios. Based on answer by Bert Evans above

    const formData = new FormData();
      formData.append("file", _file);
      formData.append("id", 7878);
      axios.post("/api/uploadFile", formData)
        .then(function (result) {
          console.log(result);
        }, function (error) {
          console.log(error);
        });

    Option 2. Using Native XMLHttpRequest()`

     var formData = new FormData();
      formData.append("file", _file);
      formData.append("id", 7878);
      var request = new XMLHttpRequest();
      request.open("POST", "/api/uploadFile");
      request.send(formData);
      request.onreadystatechange = function () {
        if (request.readyState === 4) {
          if (request.status === 200 && request.statusText === 'OK') {
            console.log('successful');
          } else {
            console.log('failed');
          }
        }
      }

    An interesting point of FormData() browser support here caniuseFormData

    Also for those trying like me to make it work with content-type = "multipart/form-data" with axios. It won't work.