el-upload以及FormData 對(duì)象上傳照片
當(dāng)我們需要上傳照片到服務(wù)器上時(shí),我們需要將照片轉(zhuǎn)換成文件流的形式。(FormData對(duì)象無法直接查看內(nèi)部屬性,需要使用get方法查看)
代碼片段
--------------------------------------------HTML--------------------------------------------
<el-upload class="upload-demo" ref="upload" action="" //必要屬性,手動(dòng)上傳可設(shè)置為空 :on-preview="handlePreview" :on-remove="handleRemove" :on-change="handleChange" //監(jiān)聽上傳文件 :auto-upload="false" //禁用自動(dòng)上傳 :show-file-list="false" //隱藏上傳文件列表 :disabled="true" //禁用自帶上傳方法 > </el-upload>
---------------------------------------------JS--------------------------------------------------
//上傳文件變化監(jiān)聽 handleChange(file, fileList){ console.log(file,fileList) this.upFile = file.raw }, //上傳 submitUpload(){ let self = this var url = api
//創(chuàng)建FormData對(duì)象,調(diào)用append方法添加參數(shù) var fd = new FormData(); fd.append("type", 1); //附件類型 fd.append("upfile", this.upFile); //文件流 fd.append("id",this.uuid); //隨機(jī)編碼 fd.append("name", "現(xiàn)場(chǎng)照片"); //附件名稱 fd.append("username", window.username); //登陸名 $.ajax({ url: url, type: 'post', dataType: 'json', data: fd, processData: false, //數(shù)據(jù)不需要處理,設(shè)置為false contentType: false, //數(shù)據(jù)類型為FormData,取消默認(rèn)設(shè)置 success: function(res) { if (res < 0){ return self.$message({ type: 'success', message: '附件添加失敗,請(qǐng)重新添加!', showClose: true, duration: 2000 }); }else{ self.$message({ type: 'success', message: '附件添加成功!', showClose: true, duration: 2000 }); self.getImg() //添加成功后,可以獲取圖片路徑以便顯示 } } }) }
遇到的問題:
1.點(diǎn)擊選擇文件會(huì)出現(xiàn)兩次彈框
el-upload自帶上傳方法,這里使用的手動(dòng)上傳,需使用disabled禁用自帶的方法
2.使用ajax時(shí),參數(shù)的格式不是json,修改默認(rèn)值
contentType:要求為String類型的參數(shù),當(dāng)發(fā)送信息至服務(wù)器時(shí),內(nèi)容編碼類型默認(rèn)為"application/x-www-form-urlencoded"。
processData:要求為Boolean類型的參數(shù),默認(rèn)為true。默認(rèn)情況下,發(fā)送的數(shù)據(jù)將被轉(zhuǎn)換為對(duì)象(從技術(shù)角度來講并非字符串)以配合默認(rèn)內(nèi)容類型"application/x-www-form-
urlencoded"。如果要發(fā)送DOM樹信息或者其他不希望轉(zhuǎn)換的信息,請(qǐng)?jiān)O(shè)置為false。
(另注: 使用axios上傳,修改請(qǐng)求頭Content-Type為multipart/form-data)

浙公網(wǎng)安備 33010602011771號(hào)