要把文件上傳的web,需要分幾步?
答:三步
第一步:創建一個上傳文件的標簽
<input type="file" id="fileExport" @change="handleFileChange" ref="inputer">
由於是在vue中,考慮到獲取節點,所以給標簽添加一個ref,方便獲取屬性並給標簽添加事件
第二步:改動事件
handleFileChange (e) {
let inputDOM = this.$refs.inputer;
this.file = inputDOM.files[0];// 通過DOM取文件數據
let size = Math.floor(this.file.size / 1024);//計算文件的大小
this.formData=new FormData();
//new一個formData事件
this.formData.append("file",this.file); //將file屬性添加到formData里
//此時formData就是我們要向后台傳的參數了
}
第三步:上傳formData
this.$http({
url:this.HOST + api.upload,
data:formData, //在此處上傳文件
method: "post",
headers:{
'Content-Type':'multipart/form-data' //值得注意的是,這個地方一定要把請求頭更改一下
}
}).then(function(res){
console.log(res,"此處應該是請求成功的回調")
}.catch(function(req){
console.log(req,"請求失敗的回調,自己看看為啥失敗")
})
})