欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

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

一、目的:

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

二、效果:

三、思路:

用input標簽自帶的上傳,先隱藏掉,給上傳按鈕添加點擊事件,綁定input的點擊事件

四、代碼:

//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
//點擊上傳按鈕
handleSelectedImg() {
?this.$refs['img-upload-input'].click()
},
?//選好圖片之后點擊打開按鈕
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// 相當于input里取得的files
? ?fd.append('stationID', data.stationID)
? ?fd.append('date', data.date)
? ?fd.append('file', fileObj)// 文件對象
? ?supplementFile(fd).then(res => {
? ? ?//調(diào)用上傳接口
? ?})
}

五、注意事項

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

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

axios request的攔截轉換直接return

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

六、常見問題

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

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

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

2.文件大小的限制問題

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

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

相關文章

最新評論