SpringBoot+vue+elementUI+minio文件上传并点击下载

页面代码

<el-form-item label="文件上传" prop="fileList">
  <el-upload
    class="upload-demo"
    :action="upLoadUrl"
    :before-remove="beforeRemove"
    :on-remove="upLoadRemove"
    :on-success="upLoadSuccess"
    :on-preview="downLoadFile"
    :file-list="fileList">
    <el-button size="small" type="primary">上传附件</el-button>
  </el-upload>
</el-form-item>

页面方法

// 用于构建文件对象
class Attach {
  constructor (file) {
    this.name = file.fileName
    this.url = file.filePath
    this.file = file
  }
}

// 文件上传成功后回调
upLoadSuccess(data) {
  if (data && data.code === 0) {
    // 将回调的后台文件对象转为前端的文件对象
    this.fileList.push(new Attach(data.fileModel))
  } else {
    this.$message.error(data.msg)
  }
},
// 点击文件进行下载
downLoadFile(file) {
  const downloadLoading = this.$loading({
    lock: true,
    text: '拼命下载中...',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  request({
    url: '/detection/file/download' + file.url,
    method: 'get',
    responseType: 'blob'
  }).then(response => {
    if (!response) {
      downloadLoading.close()
      return
    }
    let url = window.URL.createObjectURL(new Blob([response]))
    let link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', file.name)
    document.body.appendChild(link)
    link.click()
    downloadLoading.close()
  }).catch(err => {
    this.$message.error(err)
    downloadLoading.close()
  })
}

springboot代码

@GetMapping(value = "/download/{bucketName}/{folderName}/{fileName:.+}")
public void download(final HttpServletResponse response, @PathVariable String bucketName, @PathVariable String folderName, @PathVariable String fileName) {
    InputStream inputStream = null;
    try {
        String filePath = folderName + "/" +fileName;
        // 获取文件信息
        ObjectStat objectStat = minioClient.statObject(bucketName, filePath);
        // 设置响应头
        response.setHeader("content-type", objectStat.contentType());
        response.setContentType(objectStat.contentType());
        // 获取文件输入流
        inputStream = minioClient.getObject(bucketName, filePath);
        // 复制到response的输出流
        IOUtils.copy(inputStream, response.getOutputStream());
        log.info("文件:【{}】下载成功", fileName);
    } catch (Exception e) {
        log.error("文件:【{}】下载失败", fileName);
        e.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
posted @ 2021-06-03 15:20  soldier_cnblogs  阅读(1858)  评论(0编辑  收藏  举报