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

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

问题描述

首先,我检查了问题 file-upload-in-vuetifyvuetify-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 发送多个 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 对象.你不能使用 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天全站免登陆