axios文件上传 formdata,使用Axios访问作为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.

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?

});

解决方案

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.

In the frontend file

//Method to do the request

superagent

.post(/register")

.attach("avatar", uploadedImage)

uploadedImage has the image content that you get in the VueJS component

In the backend file

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

})

}

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: axios可以通过FormData对象上传文件,具体步骤如下: 1. 创建FormData对象 ``` const formData = new FormData(); ``` 2. 添加文件到FormData对象中 ``` formData.append('file', file); ``` 其中,'file'是上传文件的字段名,file是要上传的文件对象。 3. 发送请求 ``` axios.post('/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' } }).then(response => { console.log(response); }).catch(error => { console.log(error); }); ``` 其中,'/upload'是上传文件的接口地址,headers中的'Content-Type'必须设置为'multipart/form-data',否则服务器无法正确解析上传的文件。 以上就是使用axios上传文件的基本步骤。 ### 回答2: axios是现在使用最为广泛的HTTP客户端请求库,提供了方便易用的API,使用axios可以方便的进行数据的获取和提交,而且还支持跨域请求和CSRF攻击保护。 但是在上传文件时,需要使用FormData类型的数据格式进行提交,axios也提供了很好的支持。下面我们来介绍一下axios如何上传FormData类型的数据。 1. 首先需要创建FormData对象,将要上传的参数和文件添加到FormData中。 ``` let formData = new FormData(); formData.append('name', 'axios_upload_file'); // 添加普通参数 formData.append('file', file); // 添加要上传的文件 ``` 2. 创建axios实例,设置请求的参数,包括请求的URL、请求的方式、请求的数据等。需要注意的是,设置Content-Type为'multipart/form-data',这样后端服务才能正确解析请求的参数和文件。 ``` const instance = axios.create({ baseURL: 'http://localhost:3000', // 设置请求的baseURL timeout: 10000, // 设置请求的超时时间 headers: {'Content-Type': 'multipart/form-data'} // 设置请求头类型为form-data }); ``` 3. 使用axios实例发送请求,可以使用post或者put请求。传递FormData对象作为第二个参数。需要注意的是,不需要手动设置请求头中的Content-Type和Content-Length参数,axios会自动设置这些参数。 ``` instance.post('/upload', formData).then(res => { console.log(res); }).catch(err => { console.error(err); }) ``` 4. 接收后台返回的数据使用then和catch方法异步处理后台返回的数据。 ``` .then(res => { console.log(res.data); }).catch(err => { console.error(err); }) ``` 以上就是使用axios上传FormData类型的文件的步骤和注意事项了。我们需要注意,上传文件时,需要在服务端配置文件的接收处理逻辑,一般情况下需要使用multer库或其他类似的中间件,来实现文件上传相关功能。 ### 回答3: Axios是一个非常流行的JavaScript库,主要用于向服务器发起HTTP请求和处理响应。Axios支持各种HTTP请求和响应类型,包括文件上传和下载。 File Upload FormData(表单数据)是一种简单易用的方法来上传文件。FormData对象允许我们在发送XMLHttpRequest请求时添加文件以及其他类型的数据。 以下是使用Axios实现文件上传的基本步骤: 1. 创建一个FormData对象。 ``` var formData = new FormData(); ``` 2. 将要上传的文件添加到FormData对象中。 ``` formData.append('file', file); ``` 3. 发送Ajax请求,使用Axios发送FormData对象。 ``` axios.post('/url', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); ``` 在这个请求中,我们使用“POST”HTTP方法提交FormData对象,其中包含我们要上传的文件。我们还指定了Content-Type头文件类型为“multipart/form-data”。 如果文件上传成功,我们将在响应中获得服务器返回的结果。如果出现错误,我们可以通过捕获Axios Promise中的错误来进行处理。 总结:使用Axios上传文件的方式非常简单,只需要创建一个FormData对象,把要上传的文件添加到FormData对象中,然后使用Axios发送Ajax请求即可。Axios可以处理各种HTTP请求和响应类型,因此它是处理文件上传的绝佳工具。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值