elementui中el-upload自定義上傳方法中遇到的問題


由於el-upload控件中自定義的upload方法在上傳文件中是以FormData的格式上傳,后台服務器無法解析這種格式的body,所以通過http-request屬性自定義了一個上傳方法。

<el-upload
    class="upload-demo"
     ref="upload"
    action="http://127.0.0.1:5000/json/import"
    :http-request="myUpload"
    :on-preview="handlePreview"
    :on-remove="handleRemove"
    :on-error="handleError"
    :on-success="handleSuccess"
    :file-list="fileList"
    :auto-upload="false">
    <el-button slot="trigger" size="small" type="primary">選取文件</el-button>
    <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上傳到服務器</el-button>
    <div slot="tip" class="el-upload__tip">只能上傳json文件,且不超過500kb</div>
</el-upload>
 1 myUpload(content) {
 2     console.log('myUpload...');
 3     this.$axios({
 4         method: 'post',
 5         url: content.action,
 6         timeout: 20000,
 7         data: content.file
 8     }).then(res => {
 9         content.onSuccess('配時文件上傳成功')
10     }).catch(error => {
11         if (error.response) {
12             // The request was made and the server responded with a status code
13             // that falls out of the range of 2xx
14             content.onError('配時文件上傳失敗(' + error.response.status + '),' + error.response.data);
15         } else if (error.request) {
16             // The request was made but no response was received
17             // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
18             // http.ClientRequest in node.js
19             content.onError('配時文件上傳失敗,服務器端無響應');
20         } else {
21             // Something happened in setting up the request that triggered an Error
22             content.onError('配時文件上傳失敗,請求封裝失敗');
23         }
24     });
25 }

這種方式很常見,唯一要注意的點是在上傳方法調用后判斷結果成功或者失敗的時候,需要回調el-upload控件的onSuccess和onError方法,為的是能夠復用el-upload原生的一些動作,比如如果成功了,頁面上的文件列表會有一個綠勾標記上傳成功的文件,如果失敗則會把失敗的文件從文件列表中刪除,如果不回調是沒有這些功能的。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM