生活随笔
收集整理的這篇文章主要介紹了
原生JS 文件上传
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、目的:實現上傳圖片功能
二、效果:
三、思路:用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>
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
=> {})
}
五、注意事項
封裝的請求頭是(后面發現也不一定要配置這個)
'Content-Type': 'multipart/form-data;'
axios request的攔截轉換直接return
transformRequest
: [function(data
) {return data
}],
六、常見問題
1.上傳文件的同時要傳別的參數怎么辦?
可以把參數和文件裝在一個文件對象里面
let fd
= new FormData()
fd
.append('file', file
)
fd
.append('param1', param
)
2.文件大小的限制問題
前端上傳文件時限制可選文件大小后端Springboot限制nginx配置限制,當前端發送請求后端接收不到的時候,可以檢查nginx配置。
總結
以上是生活随笔為你收集整理的原生JS 文件上传的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。