java + vue 文件上传下载

一.文件上传
前端:

               <el-upload
                  ref="filepath"
                  :file-list="filepathfileList"
                  action="#"
                  :auto-upload="false"
                  :on-change="handleChange">
                  <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
                </el-upload>
                 /**
    

js

 * @description: 当文件选取发生变化时
     * @param {*} file
     * @param {*} fileList
     * @return {*}
     */
    handleChange(file, fileList) {
      if (file.type != '' || file.type != null || file.type != undefined) {
        // 计算文件的大小
        const isLt5M = file.size / 1024 / 1024 < 5 // 这里做文件大小限制
        // 如果大于50M
        if (!isLt5M) {
          this.$showMessage('上传文件大小不能超过 5MB!')
          return
        }
      }
      this.filepathfileList = fileList
      if (this.filepathfileList.length > 1) {
        this.filepathfileList.shift()
      }
      this.uploadFileRequest(file)
    },
    /**
     * @description: 文件上传
     * @param {*} fileId
     * @param {*} file
     * @return {*}
     */
    uploadFileRequest(file) {
      const param = {
        file: file.raw
      }
      uploadefile(param).then(res => {
        const path = res.data
        const arr = res.data.split('\\')
        const fileinfo = arr[arr.length - 1].split('.')
        const type = fileinfo[1]
        if (type == 'doc') {
          this.fields.filepath = path
          this.fields.filename = arr[arr.length - 1]
          this.fields.filetype = type
        } 
        this.$message.success('文件上传成功')
      }).catch(e => {
        this.$message.error('文件上传失败')
      })
    },

api

export function uploadefile(data) {
  const param = new FormData()
  Object.keys(data).forEach(key => {
    param.append(key, data[key])
  })
  return request({
    url: 'hrmContract/uploadefile',
    method: 'post',
    data: param,
    headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    }
  })
}

后端接收

 @PostMapping("/uploadefile")
    @ApiOperation("上传文件")
    public Result uploadefile(@RequestParam("file") MultipartFile file) {
        String dirPath = FileUtil.getTmpDirPath();
        String path = "";
        try {
            InputStream inputStream = file.getInputStream();
            path = dirPath + "/" + IdUtil.simpleUUID() + file.getOriginalFilename();
            File fromStream = FileUtil.writeFromStream(inputStream, path);
        } catch (IOException e) {
            throw new CrmException(SystemCodeEnum.SYSTEM_UPLOAD_FILE_ERROR);
        }
        return Result.ok(path);
    }

二:文件下载
后端根据文件地址返回文件流

    @PostMapping("/downloadfile")
    @ApiOperation("下载文件")
    public void downloadfile(HttpServletResponse response){
        try {
           String path = "文件地址";
            File file = new File(path);
            String downloadFileName = new String(file.getName().getBytes(StandardCharsets.UTF_8), "iso-8859-1");
            InputStream fis;
            fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename=" + downloadFileName);
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

前端接收后直接调用即可

downloadFileWithBuffer(data, name) {
  var downloadElement = document.createElement('a')
  var href = window.URL.createObjectURL(data) // 创建下载的链接
  downloadElement.href = href
  downloadElement.download = name // 下载后文件名
  document.body.appendChild(downloadElement)
  downloadElement.click() // 点击下载
  document.body.removeChild(downloadElement) // 下载完成移除元素
  window.URL.revokeObjectURL(href) // 释放掉blob对象
}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值