vue+axios上传图片文件和数据

项目中需要上传图片到服务器。最初思路使用input选择图片后获取base64,直接传送base64编码到后台。

<input type="file" accept="image/*" multiple @change="headImgChange" class="image_file">

在change方法里边通过FileReader()获取base64就完事了.

headImgChange( e ) {
let self = this;
let reader = new FileReader();
reader.readAsDataURL( e.target.files[ 0 ] );
reader.onload = function ( e ) {
self.headImg = e.target.result; //img base64
}
}

后面在axios.put的时候才知道后台同学使用的Django检验的是一个文件流,大概是文件流吧,据他说法需要用form表单提交.

为了顺便弄清楚form表单和ajax,决定用ajax代替form表单提交上传文件。

最浅显的区别就是form有action属性,会发生页面跳转刷新,ajax则异步请求,刷新局部。

于是一查,使用new formData();可以实现表单提交;

let data = new FormData();
data.append("user_pic",userPic); //图片
data.append("gender",gender === "男"? 1 : 0); //性别
data.append("mobile",phone); //手机号码
data.append("nickname",username); //名称

console.log( data.get("user_pic") ); //需要get才能查看到数据0.0

于是直接axios.put发送数据:

axios.put( url, data, {
headers: {
"token": window.localStorage.getItem( "token" ), //token
}
}
)
.then( res => {
let msg = res.data;
console.log( msg );
} )
.catch( err => {
console.log( err );
} )

参考这位热心网友分享的经验。

https://blog.csdn.net/qq_41688165/article/details/80834842

据他/她介绍,浏览器会自动判断类型给我们加上content-type ,自动加入的content-type里面就会有boundary;

扫描二维码关注公众号,回复: 5173877 查看本文章

 一查发的put请求,确实有这么一个content-type,感谢普及!




猜你喜欢

转载自www.cnblogs.com/otis-oc/p/10388650.html