vue+axios+nodejs+multer上传文件的坑

在做前后端分离的项目时、我们就不能使用form表单来提交数据或者上传文件了,那么就只能通过vue的axios来提交数据,如果数据中有文件类型的数据,就需要将所有需要上传的数据添加到FormData对象中,以FormData形式用axios上传,同时要设置headers中的content-type为multipart/form-data。

vue

<template>
    <div>
        <div>
            <input class="input" type="text" placeholder="用户名" v-model="username">
			<input class="input" type="password" placeholder="密码" v-model="password">
            <input type="file" name="file" accept=".jpg, .jpeg, .png" @change="changeImage">
            <input class="btn" type="button" @click="register" value="注 册"><br>
        </div>
    </div>
</template>
<script>
import axios from 'axios';
export default {
  data() {
    return {
        file: null,
		username:'',
		password:'',
    };
  },
  methods: {
        //获取文件
        changeImage (e) {
		  var file = e.target.files[0]
		  this.file = file
		},
        //注册
        register() {
           let formData= new FormData();
           formData.append('username', this.username);
		   formData.append('password', this.password1);
           formData.append("avatar", this.file);
           console.log(formData.get('avatar'))
           //请求头
           let config = {
		        headers: {
			        'Content-Type': 'multipart/form-data'
				}
           }
           //axios的post请求
           this.$axios.post('/reg',formData,config).then(res=>{
				console.log(res);
		   }).catch(err=>{
				console.log(err);
		   })
      });
    }
    }
};
</script>

nodejs

const multer = require('multer');//上传文件
//上传配置
let storage = multer.diskStorage({
    destination: function (req, file, cb) {
        // 指定路径保存
        cb(null, path.join(__dirname,'./', 'public', 'img', 'avatar'))
    },
    filename: function (req, file, cb) {
        // 将保存文件名设置为 文件原始名 + 时间戳 
        var suffix = file.originalname.split('.')
        cb(null, file.fieldname + '-' + Date.now() + '.' + suffix[suffix.length - 1]);
    }
})
// 创建中间件
let upload = multer({storage: storage});
app.post('/reg', upload.single('avatar') , function(req, res) {

	let username = req.body.username
	let password = req.body.password
	let imgname = req.file.filename;

})

 到这里,按照理论来说是完全没有问题的。但是偏偏提示服务端报错,错误原因: Multipart没有找到Boundary

首先要知道boundry是一个浏览器随机生成的一组数,用来分隔FormDatad的数据,看一下下面正确的请求头就会发现我们的请求头中没有boundry。为什么会出现这个问题?

弄了半天才知道,这是使用Express+multer中间件上传文件的时候出现的问题。multer 服务器会自动识别添加 Content-Type,重复设置 Content-Type: mutipart/form-data 就会覆盖原有的, 造成非预期的错误。

然后我就把请求头的Content-Type: mutipart/form-data设置去掉了。这次就索性没有任何数据提交到服务端了,请求头如下,Content-Type也变成了application/json默认类型。这条路根本走不通,上传文件Content-Type必须要设置为 mutipart/form-data。但是又不希望它丢失后面的boundary。

通过强大的百度,找到了造成这个问题的原因。问题的关键在axios身上,axios对我们的request做了一个拦截然后重新返回,不设置Content-Type,会默认application/json类型,这个时候我们的formData会被变为一个Object。如果自己设置Content-Type为mutipart/form-data又会丢失boundary。但是我们知道了原因在哪,就比较好解决问题。

解决方法:

1、手动设置boundary,不过这种方法改动了headers,所以不太好。

let config = {
   headers: {
    'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime()
    } 
}

2、因为axios拦截了请求,对请求的数据做了一些处理,而我们的FormData传输文件不需要任何的处理。所以可以实例一个axios上过载一个方法,躲过axios的拦截。

let myAxios = axios.create({
    baseUrl:'http://localhost:8080/',
    timeout:1000,
    headers:{"Content-Type":"multipart/form-data"}
});
Vue.prototype.$myAxios = myAxios;

this.$myAxios.post('/reg',formData).then(res=>{
	console.log(res);
}).catch(err=>{
	console.log(err);
})

3、在axios第三个参数请求的配置里添加一个transformRequest方法、覆盖掉原本的方法。transformRequest 允许在向服务器发送前,修改请求数据,但是我们不需要修改数据。

let config = {
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    transformRequest: [function (data) {
       return data
    }]
}

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值