前端vue怎么实现文件上传

本文前提是使用vue.js+element-ui结合,借用element-ui的upload上传附件组件来实现前端vue怎么上传附件(图片,Excel,视频等)

1、data.js中定义

export default{
     init :function(){
          return{
                 fileList:[],
                 token:{
                    accessToken:''
                 }
           }
     }
}

2、xxx.vue中

<template>
    <section>
        <el-row> 
             <el-form-item>
                  <el-upload 
                         class="upload-demo"  
                         action="http://192.168.400.56:9000/file/rest/common/uploadFilesClientByArray" 
                         :data='token'
                         :on-change="handleChange" 
                         :on-remove="handleRemove" 
                         :file-list="fileList">
                        <el-button size="small" type="primary">上传附件</el-button> 
                  </el-upload>  
                 </el-form-item> 
        </el-row>
    </section>
</template>
<script>
    import data from './data';
    import methods from './method';
    export default{
        data() {  
            return data.init(); 
        },
        methods:methods
    }
</script>
<style>
</style>

注:1、接口接收accessToken的值放在请求头中,将上面的:data=”token” 改成:headers=”token”即可
2、action即为附件的上传接口的详细地址
3、data是传递参数的
4、fileList是上传回调的数据数组

3、method.js中

export default{
    handleChange(file, fileList) {
        this.fileList = fileList; 
        var ids=handleUpOrDel(fileList);  
    },  
    handleRemove(file, fileList){
        this.fileList = fileList;  
        var ids=handleUpOrDel(fileList);
    },
    handleUpOrDel(fileList){
       let ids="";
       if(fileList){
            for(var i =0; i < fileList.length; i++){ 
                console.log(fileList[i].response);
                var obj = fileList[i].response; 
                if(obj){
                    if(obj.code){
                         ids +=obj.record.successResponse[0].id;
                         if(i < fileList.length - 1){
                            ids +=",";
                         }
                    }
                }
            } 
        }
        return ids;  
    }
}

回调之后的结果如下图所示:

前端vue怎么实现文件上传_第1张图片

你可能感兴趣的:(vue)