使用ElementUI中的upload元件上傳Excel檔案
阿新 • • 發佈:2018-11-21
最初使用該元件實現圖片上傳是沒有問題的,前後端配合,最終實現想要的效果,元件使用過程式碼如下:
<el-upload class='image-uploader' :multiple='true' :auto-upload='true' list-type='picture' :show-file-list='false' :before-upload="beforeUpload" :drag='true' action='' :http-request="uploadFile" > <div class="el-upload__text">將檔案拖到此處,或<em>點選上傳</em></div> </el-upload>
現在改為使用該元件實現Excel檔案上傳,元件的使用幾乎是不變的,程式碼如下:
<el-upload class='image-uploader' :multiple='false' :auto-upload='true' list-type='text' :show-file-list='true' :before-upload="beforeUpload" :drag='true' action='' :limit="1" :on-exceed="handleExceed" :http-request="uploadFile" > <i class="el-icon-upload"></i> <div class="el-upload__text">將檔案拖到此處,或<em>點選上傳</em></div> <div class="el-upload__tip" slot="tip">一次只能上傳一個檔案,僅限text格式,單檔案不超過1MB</div> </el-upload>
觸發的方法如下程式碼:
// 上傳檔案之前的鉤子 beforeUpload (file) { console.log('beforeUpload') console.log(file.type) const isText = file.type === 'application/vnd.ms-excel' const isTextComputer = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' return (isText | isTextComputer) }, // 上傳檔案個數超過定義的數量 handleExceed (files, fileList) { this.$message.warning(`當前限制選擇 1 個檔案,請刪除後繼續上傳`) }, // 上傳檔案 uploadFile (item) { console.log(item) const fileObj = item.file // FormData 物件 const form = new FormData() // 檔案物件 form.append('file', fileObj) form.append('comId', this.comId) console.log(JSON.stringify(form)) // let formTwo = JSON.stringify(form) EnterAPI.iExcel(form).then(response => { console.log('MediaAPI.upload') console.log(response) this.$message.info('檔案:' + fileObj.name + '上傳成功') }) }
上述程式碼是可以跑通的前端程式碼,我在除錯的過程中,遇到問題是報錯Status Code: 415 Unsupported Media Type。我在查資料的過程中,部分解決方案都指向content-type,因此我換成使用axios請求,帶上content-type:application/json;charset=UTF-8;仍然報同樣的錯誤,同時也有一種解決方式是所傳的物件form,對他進行一個轉化,但是同樣遇到上述報錯。
在這之後將問題拋向後臺,發現使用該程式碼請求介面的時候,斷點進不去,因此斷定是後臺接收型別有問題,最終得以解決。