使用Axios访问作为FormData发送的数据 [英] Accessing data sent as FormData using Axios
问题描述
我有一个用VueJS编写的应用程序,我将用户上传的文件发送到后端.为此,我使用Axios,并将文件作为FormData发送.问题是当我在后端时,我不知道如何访问FormData中的字段.
I have an application written in VueJS where I send a file, that the user uploads, to the backend. To do this I'm using Axios and I'm sending the file as a FormData. The problem is that I don't know how to access the fields in FormData when I'm in the backend.
我已经使用axios发送了一个文件,如下所示:
I've sent a file using axios like this:
onUpload(): void {
if(this.fileChosen){
const fd = new FormData();
fd.append('file', this.selectedFile, this.selectedFile.name);
axios.post('http://localhost:8080/routes', fd, {
onUploadProgress: uploadEvent => {
console.log('Upload Progress' + Math.round(uploadEvent.loaded / uploadEvent.total) * 100 + " %");
}
})
.then(
res => {
console.log(res);
});
} else {
this.fileMsg = "You haven't chosen a file";
}
}
}
然后在我的后端中,我要访问我发送的该文件:
Then in my backend I want to access this file that I sent:
app.post('/routes', function(req, res){
res.set("Access-Control-Allow-Origin", "*");
// Here I want to access my file! But how?
});
推荐答案
我在使用 axios 上传文件时遇到问题,因此可以使用模块 superagent ( https://github.com/visionmedia/superagent ),该文件支持使用formData上传文件.然后,在后端,您需要使用 multer ( https://github.com /expressjs/multer ),以获取文件.
I had problems with using axios for file uploading so you can use the module superagent (https://github.com/visionmedia/superagent) that supports file uploading with formData. Then, in the backend, you need to use multer (https://github.com/expressjs/multer), to get the file.
在前端文件中
//Method to do the request
superagent
.post(/register")
.attach("avatar", uploadedImage)
uploadedImage具有您在VueJS组件中获得的图像内容
uploadedImage has the image content that you get in the VueJS component
在后端文件中
var multer = require('multer')
var upload = multer({ dest: 'uploads/' })
import fs from 'fs-extra'
router.post('/register', upload.single('avatar'), (req, res, next) => {
return fs.readFile(req.file.path)
.then(content => {
// The content of the file
})
}
使用此代码,每次您将文件内容上载到formdata中的文件/register时,图像将存储在后端的/uploads文件夹中.请注意,图像密钥的前端和后端必须相同,在这种情况下为头像.
With this code, everytime you upload a file to /register with the file content in the formdata, your image will be stored in /uploads folder on your backend. Please note that the image key must be the same in the frontend and backend, in this case, avatar.
这篇关于使用Axios访问作为FormData发送的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!