vuejs的post请求怎么发送文件?body中的formdata怎么构造

我想向后台传一个zip压缩包configuration.zip,现在已通过element-ui的upload控件将文件上传了,这个控件的地址是:
http://element.eleme.io/#/zh-...
感觉还可以,现在需要调用post请求,将这个zip文件发送到后台,以formdata的形式发送,在postman中发送的形式如图,这样是可以的,后台已写好:
图片描述
但不知道用vue-resource的post请求该怎么构造这个formdata,我现在用下面这种方式是不行的,不太懂,还希望有大神指导下:

        this.$http.post('/url', {filename: 'http://localhost:8080/url/configuration.zip'}).then(function(response) {
            return response.text();
        },function(err) {
            alert("goodbye world")
            console.log(err)
        }).then((text) => {
            this.msg = text
        });

上传zip文件后如下:
图片描述

看vue-resource的github上(链接:https://github.com/pagekit/vu...)的说明给的例子是这样的:

this.$http.post('/someUrl', {foo: 'bar'}).then((response) => {…}, (response) => {
    // error callback
  });

但和我这个需求好像不太一样,求指教 :-)

阅读 24.2k
3 个回答

参考@lockdown 提供的链接https://developer.mozilla.org...给出的方法,可以实现,感谢 :-)

具体方法是在script中先建一个全局变量:

var zipFormData = new FormData();

然后根据提供的方法添加向formdata中添加数据:

zipFormData.append('filename', file, 'test.zip');//filename是键,file是值,就是要传的文件,test.zip是要传的文件名

然后再用vue-resource的post请求发送即可:

        this.$http.post('/url', zipFormData).then(function(response) {
            return response.text();
        }, function(err) {
            alert("goodbye world")
            console.log(err)
        }).then((text) => {
            this.msg = text;
            alert(this.msg);
        });

关键在于file取值

zipFormData.append('filename', file, 'test.zip');
//filename是键,
//file是值(document.getElementById('file').files[0]),就是要传的文件,
//test.zip是要传的文件名

我也遇到过这个问题,开始没理解透 file 的取值问题,后来在 这里 看到了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题