vue.js+elementUI文件上传、文件导入、文件下载

1.文件下载

<el-button plain @click ="exportVmExcel()"  size='mini' icon="el-icon-download" style="margin-left:10px;">模板下载</el-button>

exportVmExcel() {
    var language = i18n.locale;
    console.log("language==="+language);
    //模板下载
    Api.templateDownload(language).then(res => {
        if (res) {
            self.handlerDownloadResult({
                res: res,
                optionType: "vm-template"
            });
        }
    })
     
},

//API写法,用户模板下载
templateDownload(language) {
    return axios({
    method: 'get',
    url: '/api/vmachine/download/template?language='+language,
    responseType: 'blob'
    })
},

 

2.文件导入

<el-button size='mini' @click="chooseFile" ref="upload"> <i class="fa fa-share" > </i>&nbsp;&nbsp;{{$t('导入')}}</el-button>
<input type="file" v-if = "ishowFile" style="display: none" name ="attence" @change="changeFile($event)" ref ="attenceInput" aria-hidden="true">
<input type="file"    style="display: none" name ="attence" @change="changeFile($event)" ref ="attenceInput" aria-hidden="true">

//批量导入,选择文件
chooseFile(){
    let isTerminal = this.selectTenant
    if(isTerminal){
        if(this.jumpOrDialog.tenantId == ''){
            this.$message({
                message: this.$t('text.vmValidates.message6'),
                type: "warning"
            });
            return
        }
    }
    this.$refs.attenceInput.click();
    this.ishowFile = false // 销毁
},
changeFile(val){
    this.quantityImport(val)
},
quantityImport(val){
    let isLt5M = val.target.files[0].size / 1024 / 1024 <= 5;
    this.selectedFile = val.target.files[0];    
    if (this.isExcel() == true && isLt5M == true) {
        let isTerminal = this.selectTenant;
        let tenantId = '';
        let tenantName = '';
        if(isTerminal){
            tenantId = this.jumpOrDialog.tenantId
            tenantName = this.jumpOrDialog.tenantName
        }else{
            let userInfo = JSON.parse(localStorage.getItem("userInfo"))
            tenantId = userInfo.tenantId
            tenantName = userInfo.tenantName
        }
        let vmData = {
            tenantId: tenantId,
            pageNum: this.pageNum,
            pageSize: this.pageSize
        }
        let formdata = new FormData();
        formdata.append('file', this.selectedFile);
        var map = {
            formdata:formdata,
        }
        Api.batchImport(map,tenantId,tenantName,this.createUserId,this.createUserName).then(res => {
            if(res.status == '200'){
                this.$message.success(this.$t('112.uploadSuccess'));
                this.getAllVmRegister(vmData)
                this.selectedFile = "" 
                this.ishowFile = true
            }else{
                this.$message({ 
                    message: this.$t('264845'),
                    type: "error",
                    showClose: true,
                    duration:6000,
                });
               // this.$message.error(this.$t('ploadFailue'));
                this.getAllVmRegister(vmData)
            }
        }).catch( re => {
            if(re.response.data.code == '110'){
                var errMessages1 = re.response.data.message;
                this.$message({
                    type: 'error',showClose: true,duration:6000,
                    message: this.$t('1352.79865.23)
                });
            }else{
                this.$message({
                    type: 'error',showClose: true,duration:6000,
                    message:  this.$t('15973')
                });
            }
        })
    }
    this.selectedFile = "" 
    this.ishowFile = true
},
isExcel() {
    let self = this;
    let filename = self.selectedFile.name;
    let arr = filename.split('.');
    if (arr[1] !== 'xls') {
        console.log(this.$t('12356'));
      this.$message({ 
          message: this.$t('123123'),
          type: "error",
          showClose: true,
          duration:6000,
          });
    
        return false;
    } else {
    return true;
    }
},

 

//API批量新增

batchImport: (data,tenantId,tenantName,createUserId,createUserName) => {
    return axios({
        method: 'post',
        header: {
            "Content-Type": "multipart/form-data",
        },
        url:`/api/vmachine/register/batch?` +'tenantId='+tenantId+'&tenantName='+tenantName+'&createUserId='+createUserId+'&createUserName='+createUserName, 
        data: data.formdata
    })
},

 

3、后端

@RequestMapping(value = "/downloadfile", method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public String downloadFile(@RequestParam("Id")Integer Id,
                                         HttpServletRequest request, HttpServletResponse response) {
        if (Id == null) {
            return null;
        }
        try {
            //文件路径
            String signFileUrl = "";
            outputStream(request, response, "application/octet-stream",getUploadPathData() + signFileUrl);
            return null;
        } catch (Exception e) {
            logger.error("下载失败", e);
            throw new ServiceException("下载文件异常");
        }
    }


    private String getUploadPathData() {
        String rootPath = UhomePropUtils.getProperty("PATH");
        StringBuilder sb = (new StringBuilder()).append(rootPath);
        if (!rootPath.endsWith("/")) {
            sb.append("/");
        }
        return sb.toString();
    }


    /**
     * 下载文件
     * @param request
     * @param response
     * @param contentType
     * @param fileName  文件全路径
     */
    public static void outputStream(HttpServletRequest request, HttpServletResponse response, String contentType, String fileName) {
        if (StringUtils.isEmpty(fileName)) {
            return;
        }
        InputStream input = null;
        OutputStream output = null;
        File file = null;
        String outFileName = fileName.substring(fileName.lastIndexOf("/")+1);
        try {
            file = new File(fileName);
            if(!file.exists()){
                file.mkdirs();
            }
            file.setReadable(true);
            file.setWritable(true);//设置其他用户可读
            response.setCharacterEncoding("UTF-8");
            response.setContentType(contentType);
            response.setHeader("Content-disposition", "attachment; filename=" + new String(outFileName.getBytes("UTF-8"), "iso8859-1"));
            input = new FileInputStream(file);
            output = response.getOutputStream();
            IOUtils.copy(input, output);
        } catch (Exception ex) {
            // 以后处理异常
        } finally {
            IOUtils.closeQuietly(input);
            IOUtils.closeQuietly(output);
        }
    }

 

posted on 2019-03-18 10:49  鲁班快跑  阅读(168)  评论(0编辑  收藏  举报