vue+axios上傳圖片文件和數據

項目中須要上傳圖片到服務器。最初思路使用input選擇圖片後獲取base64,直接傳送base64編碼到後臺。ios

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

在change方法裏邊經過FileReader()獲取base64就完事了.ajax

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表單提交.axios

爲了順便弄清楚form表單和ajax,決定用ajax代替form表單提交上傳文件。瀏覽器

最淺顯的區別就是form有action屬性,會發生頁面跳轉刷新,ajax則異步請求,刷新局部。服務器

因而一查,使用new formData();能夠實現表單提交;app

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 );
} )

 

參考這位熱心網友分享的經驗。this

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

據他/她介紹,瀏覽器會自動判斷類型給咱們加上content-type ,自動加入的content-type裏面就會有boundary;url

 一查發的put請求,確實有這麼一個content-type,感謝普及!

相關文章
相關標籤/搜索