亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

原生JS實(shí)現(xiàn)文件上傳

 更新時(shí)間:2022年07月17日 10:51:45   作者:Tiny2017  
這篇文章主要為大家詳細(xì)介紹了原生JS實(shí)現(xiàn)文件上傳,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了JS實(shí)現(xiàn)文件上傳的具體代碼,供大家參考,具體內(nèi)容如下

一、目的:

實(shí)現(xiàn)上傳圖片功能

二、效果:

三、思路:

用input標(biāo)簽自帶的上傳,先隱藏掉,給上傳按鈕添加點(diǎn)擊事件,綁定input的點(diǎn)擊事件

四、代碼:

//html
<input ref="img-upload-input" class="img-upload-input" type="file" accept=".png, .jpg" @change="submitUpload">
<el-button style="margin-top: 20px" type="primary" @click="handleSelectedImg">選擇圖片</el-button>
//js
//點(diǎn)擊上傳按鈕
handleSelectedImg() {
?this.$refs['img-upload-input'].click()
},
?//選好圖片之后點(diǎn)擊打開按鈕
submitUpload(e) {
? const files = e.target.files
? const rawFile = files[0] // only use files[0]
? if (!rawFile) return
? this.upload(rawFile)
},
?//上傳
upload(rawFile) {
? ?this.$refs['img-upload-input'].value = null // fix can't select the same excel
? ?if (!this.beforeUpload) {
? ? ?return
? ?}
? ?//檢查文件是否滿足條件
? ?const before = this.beforeUpload(rawFile)
? ?if (before) {
? ?//上傳事件
? ? ?this.uploadSectionFile(this.uploadParams, rawFile)
? ?}
},
beforeUpload(file) {
? ?const isLt1M = file.size / 1024 / 1024 < 50

? ?if (isLt1M) {
? ? ?return true
? ?}
? ?console.log('上傳文件不超過50M', 'warning')
? ?return false
},
uploadSectionFile(params, file) {
? ?let data = params
? ?let fd = new FormData()// FormData 對象
? ?let fileObj = file// 相當(dāng)于input里取得的files
? ?fd.append('stationID', data.stationID)
? ?fd.append('date', data.date)
? ?fd.append('file', fileObj)// 文件對象
? ?supplementFile(fd).then(res => {
? ? ?//調(diào)用上傳接口
? ?})
}

五、注意事項(xiàng)

封裝的請求頭是(后面發(fā)現(xiàn)也不一定要配置這個(gè))

'Content-Type': 'multipart/form-data;'

axios request的攔截轉(zhuǎn)換直接return

transformRequest: [function(data) {
? ? // 對 data 進(jìn)行任意轉(zhuǎn)換處理
? ? return data
? }],

六、常見問題

1.上傳文件的同時(shí)要傳別的參數(shù)怎么辦?

可以把參數(shù)和文件裝在一個(gè)文件對象里面

let fd = new FormData()
fd.append('file', file)//文件
fd.append('param1', param)

2.文件大小的限制問題

1)、前端上傳文件時(shí)限制可選文件大小
2)、后端Springboot限制
3)、nginx配置限制,當(dāng)前端發(fā)送請求后端接收不到的時(shí)候,可以檢查nginx配置。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論