elementui中el-upload自定义上传方法中遇到的问题

时间:2018-01-17 13:53:13   收藏:0   阅读:17837

由于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原生的一些动作,比如如果成功了,页面上的文件列表会有一个绿勾标记上传成功的文件,如果失败则会把失败的文件从文件列表中删除,如果不回调是没有这些功能的。

技术分享图片

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!