如何提交“多部分/表单数据"来自VueJs [英] how to submit "multipart/form-data" from VueJs

查看:386
本文介绍了如何提交“多部分/表单数据"来自VueJs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在前端使用VueJs/axios,在nodejs中使用multer,以使简单的文件上传正常工作.

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

到目前为止,所有尝试均未成功. 尽管可以使用ng-upload和其他类似插件以角度1/2的方式以100种方式实现.但是VueJs似乎缺少此基本功能. 根据我的研究,axios不支持"multipart/form-data".引用 https://github.com/mzabriskie/axios/issues/789 .

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和其他nodejs库似乎可以从1/2角度无缝处理"multipart/form-data".但是,VueJ无法使用相同的功能.

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.

除了axios之外,还有其他替代方法可以支持"multipart/form-data"吗?WebKitFormBoundary ??

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

非常感谢

推荐答案

我在VueJs中找到了两种实现此目的的方法.可能还有更多.

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

选项1.使用Axios.根据上述Bert Evans的回答

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

选项2.使用本机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');
      }
    }
  }

这里的FormData()浏览器支持的有趣之处 caniuseFormData

An interesting point of FormData() browser support here caniuseFormData

对于那些像我这样尝试使其与axios一起使用content-type ="multipart/form-data"的人也是如此.它不会工作.

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

这篇关于如何提交“多部分/表单数据"来自VueJs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆