溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

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

發(fā)布時間:2022-07-18 09:35:51 來源:億速云 閱讀:337 作者:iii 欄目:開發(fā)技術(shù)

本篇內(nèi)容主要講解“怎么用原生JS實現(xiàn)文件上傳”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“怎么用原生JS實現(xiàn)文件上傳”吧!

一、目的:

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

二、效果:

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

三、思路:

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

四、代碼:

//html
<input ref="img-upload-input" class="img-upload-input" type="file" accept=".png, .jpg" @change="submitUpload">
<el-button  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的攔截轉(zhuǎn)換直接return

transformRequest: [function(data) {
    // 對 data 進行任意轉(zhuǎn)換處理
    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配置。

到此,相信大家對“怎么用原生JS實現(xiàn)文件上傳”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關內(nèi)容可以進入相關頻道進行查詢,關注我們,繼續(xù)學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

js
AI