使用vuetify 2 v-file-input和axios上传文件 [英] File Upload using vuetify 2 v-file-input and axios

查看:1579
本文介绍了使用vuetify 2 v-file-input和axios上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我已经检查了问题 file-upload-in-vuetify vuetify-file-uploads .但是那里的解决方案不起作用.

First of all, i've checked questions file-upload-in-vuetify and vuetify-file-uploads. But the solutions there didn't work.

我正在尝试使用vuetify 2 <v-file-input>发送多个PDF文件.我创建了FormData对象并附加了所有文件,但是当我尝试提交该文件时,它没有到达后端.我只是得到一个空物体.这是我的代码:

I'm trying to use vuetify 2 <v-file-input> to send multiple PDF files. I created the FormData object and appended all my files but when i attempt to submit it doesn't reach my backend. I just get an empty object. this is my code:

模板:

<v-layout>
    <v-flex>
      <v-file-input show-size counter chips multiple label="Arquivo Geral" ref="myfile" v-model="files"></v-file-input>
    </v-flex>
    <v-flex>
      <v-btn color="primary" text @click="submitFiles">test</v-btn>
    </v-flex>
</v-layout>

脚本:

data() {
    return {
        files: null,
    }
}
methods: {
    submitFiles(){
        let formData = new FormData()

        if(this.files){

            for( let file in this.files){
                formData.append("cave", file)
            }

            console.log(formData.getAll("cave"))
            console.log(this.files)
            axios.post('https://eniwp6w65oc77.x.pipedream.net/', 
                        {
                            files: formData,
                            test: "test"
                        }, 
                        { 
                            headers: { 
                                'Content-Type': 'multipart/form-data'
                            } 
                        }).then( response => {
                            console.log('Success!')
                            console.log({response})
                        }).catch(error => {
                            console.log({error})
                        })
        }
        else {
            console.log('there are no files.')
        }
    }
}

我的响应正文和requestbin中的标头:

my response body and header in requestbin:

正文:

{
    "files": {},
    "test": "test"
}

标题:

host: eniwp6w65oc77.x.pipedream.net
Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,pt;q=0.8,gl;q=0.7
Cache-Control: no-cache
Content-Type: multipart/form-data
Origin: http://localhost:8000
Pragma: no-cache
Referer: http://localhost:8000/
Sec-Fetch-Mode: cors
Sec-Fetch-Site: cross-site
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36
Content-Length: 28
Connection: keep-alive

推荐答案

首先,您在代码中有两个错误:

First of all, you have two bugs in code:

  1. 准备FormData对象的位置.您不能在rel ="noreferrer"> for-in 循环在此处迭代文件数组,因为for-in循环遍历对象的可枚举属性名称.您可以使用 for-of 循环代替.

  1. Where you're preparing FormData object. You can't use for-in loop for iterating an array of files here since for-in loops over enumerable property names of an object. You can use for-of loop instead.

您在方括号中使用formData.您应该传递FormData实例,而不是JSON.要使用FormData发送诸如"test"之类的附加参数,请执行formData.append("test", "foo bar")

You're using formData in brackets. You should pass FormData instance, not JSON. To send aditional paramaters like "test" using FormData do formData.append("test", "foo bar")

还要检查后端是否正确处理了multipart/form-data数据.如果后端位于Node.jsExpress.js中,则应使用正确的正文解析器中间件,例如 multer

Also check that your backend properly handles multipart/form-data data. If your backend is in Node.js and Express.js then you should use proper body parser middleware, for example multer

这是一个有效的示例:

Node.js/Express.js后端:

Node.js/Express.js backend:

const multer = require("multer"),
...    
router.post("/upload-files", multer().array("files"), function (req, res) {
    console.log("body: ", req.body);
    console.log("files:", req.files);
    return res.sendStatus(200);
});

前端:

submitFiles() {
    if (this.files) {
        let formData = new FormData();

        // files
        for (let file of this.files) {
            formData.append("files", file, file.name);
        }

        // additional data
        formData.append("test", "foo bar");

        axios
            .post("/upload-files", formData)
            .then(response => {
                console.log("Success!");
                console.log({ response });
            })
            .catch(error => {
                console.log({ error });
            });
    } else {
        console.log("there are no files.");
    }
}

请注意,当您将FormData作为POST请求正文传递时,无需手动设置Content-Type标头

Note that you don't need to set Content-Type header manually when you pass FormData as a POST request body

这篇关于使用vuetify 2 v-file-input和axios上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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