生活随笔
收集整理的這篇文章主要介紹了
原生JS 文件上传
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
一、目的:實(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>
handleSelectedImg() {this.$refs
['img-upload-input'].click()
},
submitUpload(e
) {const files
= e
.target
.files
const rawFile
= files
[0] if (!rawFile
) returnthis.upload(rawFile
)
},
upload(rawFile
) {this.$refs
['img-upload-input'].value
= null if (!this.beforeUpload
) {return}const before
= this.beforeUpload(rawFile
)if (before
) {this.uploadSectionFile(this.uploadParams
, rawFile
)}
},
beforeUpload(file
) {const isLt1M
= file
.size
/ 1024 / 1024 < 50if (isLt1M
) {return true}console
.log('上傳文件不超過50M', 'warning')return false
},
uploadSectionFile(params
, file
) {let data
= params
let fd
= new FormData()let fileObj
= filefd
.append('stationID', data
.stationID
)fd
.append('date', data
.date
)fd
.append('file', fileObj
)supplementFile(fd
).then(res
=> {})
}
五、注意事項(xiàng)
封裝的請求頭是(后面發(fā)現(xiàn)也不一定要配置這個(gè))
'Content-Type': 'multipart/form-data;'
axios request的攔截轉(zhuǎn)換直接return
transformRequest
: [function(data
) {return data
}],
六、常見問題
1.上傳文件的同時(shí)要傳別的參數(shù)怎么辦?
可以把參數(shù)和文件裝在一個(gè)文件對象里面
let fd
= new FormData()
fd
.append('file', file
)
fd
.append('param1', param
)
2.文件大小的限制問題
前端上傳文件時(shí)限制可選文件大小后端Springboot限制nginx配置限制,當(dāng)前端發(fā)送請求后端接收不到的時(shí)候,可以檢查nginx配置。
總結(jié)
以上是生活随笔為你收集整理的原生JS 文件上传的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。