日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

原生JS 文件上传

發布時間:2023/12/10 javascript 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 原生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> //js //點擊上傳按鈕 handleSelectedImg() {this.$refs['img-upload-input'].click() },//選好圖片之后點擊打開按鈕 submitUpload(e) {const files = e.target.filesconst rawFile = files[0] // only use files[0]if (!rawFile) returnthis.upload(rawFile) },//上傳 upload(rawFile) {this.$refs['img-upload-input'].value = null // fix can't select the same excelif (!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 = paramslet fd = new FormData()// FormData 對象let fileObj = file// 相當于input里取得的filesfd.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) {// 對 data 進行任意轉換處理return data}],

六、常見問題
1.上傳文件的同時要傳別的參數怎么辦?
可以把參數和文件裝在一個文件對象里面

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

2.文件大小的限制問題

  • 前端上傳文件時限制可選文件大小
  • 后端Springboot限制
  • nginx配置限制,當前端發送請求后端接收不到的時候,可以檢查nginx配置。
  • 總結

    以上是生活随笔為你收集整理的原生JS 文件上传的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。