springboot + vue 文件下载

这段代码展示了后端如何处理文件下载,根据文件存储在MinIO或OSS上的情况选择不同的获取方式,并设置响应头以触发浏览器下载。同时,前端使用Axios封装了一个下载文件的方法,通过GET请求并指定responseType为'blob'来实现文件下载。当文件下载请求成功时,前端创建一个隐藏的a标签,设置下载属性并触发点击完成文件下载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

后端代码

/**
* 文件下载
* @param filePath 文件名/文件根路径+文件名 如 test\test.docx
* @param uploadpath 文件存储路径   如: d:\temp
* @param uploadType 本地文件传  local
* @param response
*/
public void viewAndDownload(String filePath, String uploadpath, String uploadType, HttpServletResponse response) {
        InputStream inputStream = null;
        ServletOutputStream outputStream = null;

        try {
            String fileName;
            String bucketName;
            if (filePath.startsWith("http")) {
                fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
                String objectName;
                if ("minio".equals(uploadType)) {
                    bucketName = filePath.replace(MinioUtil.getMinioUrl(), "").split("/")[0];
                    objectName = filePath.replace(MinioUtil.getMinioUrl() + bucketName, "");
                    inputStream = MinioUtil.getMinioFile(bucketName, objectName);
                    if (inputStream == null) {
                        bucketName = "eoafile";
                        objectName = filePath.replace(OssBootUtil.getStaticDomain() + "/", "");
                        inputStream = OssBootUtil.getOssFile(objectName, bucketName);
                    }
                } else {
                    bucketName = "eoafile";
                    objectName = filePath.replace(OssBootUtil.getStaticDomain() + "/", "");
                    inputStream = OssBootUtil.getOssFile(objectName, bucketName);
                    if (inputStream == null) {
                        bucketName = filePath.replace(MinioUtil.getMinioUrl(), "").split("/")[0];
                        objectName = filePath.replace(MinioUtil.getMinioUrl() + bucketName, "");
                        inputStream = MinioUtil.getMinioFile(bucketName, objectName);
                    }
                }

                response.addHeader("Content-Disposition", "attachment;fileName=" + new String(fileName.getBytes("UTF-8"), "iso-8859-1"));
            } else {
                filePath = filePath.replace("..", "");
                if (filePath.endsWith(",")) {
                    filePath = filePath.substring(0, filePath.length() - 1);
                }

                fileName = uploadpath + File.separator + filePath;
                bucketName = uploadpath + File.separator + fileName;
                File file = new File(bucketName);
                inputStream = new BufferedInputStream(new FileInputStream(fileName));
                response.addHeader("Content-Disposition", "attachment;fileName=" + new String(file.getName().getBytes("UTF-8"), "iso-8859-1"));
            }

            response.setContentType("application/force-download");
            outputStream = response.getOutputStream();
            if (inputStream != null) {
                byte[] buf = new byte[1024];

                int len;
                while((len = ((InputStream)inputStream).read(buf)) > 0) {
                    outputStream.write(buf, 0, len);
                }

                response.flushBuffer();
            }
        } catch (IOException var22) {
            response.setStatus(404);
            this.log.error("预览文件失败" + var22.getMessage());
        } finally {
            if (inputStream != null) {
                try {
                    ((InputStream)inputStream).close();
                } catch (IOException var21) {
                    this.log.error(var21.getMessage(), var21);
                }
            }

            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException var20) {
                    this.log.error(var20.getMessage(), var20);
                }
            }

        }

    }

前端代码


//axios封装
export function downFile(url, parameter) {
  return axios({
    url: url,
    params: parameter,
    method: 'get',
    responseType: 'blob'
  })
}



exportData(){
   var params = this.getQueryParams();//查询条件
   delete params.entrustStartTimeSearch
   delete params.testStartTimeSearch
   this.loading = true;
   downFile(this.url.exportData,params).then((data)=>{
     if (!data) {
       this.$message.warning("导出失败")
       return
     }
     let url = window.URL.createObjectURL(new Blob([data]));
     let link = document.createElement('a');
     link.style.display = 'none';
     link.href = url;
     link.setAttribute('download', '试验设备时长统计表.xlsx');
     document.body.appendChild(link);
     link.click()
     this.$message.success("导出成功!")
     this.loading = false;
   })
 }

### 回答1: Spring Boot + Vue 文件下载可以通过以下步骤实现: 1.Vue 中创建一个下载按钮,当用户点击该按钮时,发送一个请求到后端。 2.Spring Boot 中创建一个 RESTful API,该 API 接收文件下载请求,并返回文件的字节流。 3.Vue 中接收到后端返回的文件字节流后,使用 Blob 对象将其转换为文件,并通过浏览器下载文件。 具体实现细节可以参考以下链接: https://www.baeldung.com/spring-boot-file-download https://www.tutorialspoint.com/vuejs/vuejs_file_download.htm ### 回答2: Spring Boot是一种开源的Java框架,它提供了一个快速搭建Java Web应用程序的方法。Vue.js是一个非常流行的JavaScript框架,它提供了一个高效且易于使用的前端开发平台。在一些复杂的Web应用中,文件下载是必不可少的一个功能,尤其是在网站中提供一些用户需要的PDF、图片、动画或其他二进制文件。本文将会讨论在Spring Boot框架下如何使用Vue.js实现文件下载。 1. 后端实现: 首先,我们需在后端实现下载文件的接口。使用Spring Boot框架的话,我们需要建立一个Restful的API接口来实现该功能。具体实现方式如下: @GetMapping(value = "/downloadFile") public ResponseEntity<byte[]> downloadPostmanCollectionFile() throws FileNotFoundException { byte[] fileData = getFileData();//获取文件数据 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_PDF);//设置Content-Type为PDF headers.setContentDispositionFormData("attachment", "test.pdf");//设置响应头信息 headers.setContentLength(fileData.length); return new ResponseEntity<>(fileData, headers, HttpStatus.OK);//返回ResponseEntity对象 } 需要注意的是,我们需要根据实际需求设置Content-Type和对应的文件名。 2. 前端实现: 在Vue.js中实现文件下载功能需要通过发送请求来触发后端服务的下载方法。需要使用axios或者其他类似的网络请求库实现。具体代码如下: methods: { downloadFile () { axios({ method: 'get', url: '/downloadFile', responseType: 'blob' }).then(res => { const url = window.URL.createObjectURL(new Blob([res.data])) const link = document.createElement('a') link.style.display = 'none' link.href = url link.setAttribute('download', 'test.pdf') document.body.appendChild(link) link.click() document.body.removeChild(link) }) } } 在该代码中,我们首先向后端发送请求,后端会返回一个二进制数据流(blob)。我们将数据封装成一个Blob对象,并将其转换为一个URL,然后通过a标签创建一个下载链接,并模拟点击该链接即可实现文件下载。需要注意的是,我们需要根据实际返回的响应格式设置responseType属性。 综上所述,Spring Boot Vue文件下载功能的实现方法就是创建一个Restful后端接口,并在前端使用axios向该接口发送请求,获取文件数据,并将其转换为Blob对象,创建下载链接即可。如果使用Vue.js作为前端框架,可以通过一个函数封装下载的全部过程,实现一键下载的功能。 ### 回答3: Spring Boot Vue文件下载需要在后端代码中构建下载文件的接口,同时在前端代码中实现文件下载的功能。以下是具体实现步骤: 1.后端代码实现 在Spring Boot中,需要通过编写Controller的方法来生成下载文件的接口。下面是一个简单的示例: ``` @GetMapping("/download") public ResponseEntity<Object> downloadFile() throws IOException { String fileName = "example.txt"; File file = new File(fileName); InputStreamResource resource = new InputStreamResource(new FileInputStream(file)); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName())); headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); headers.add("Pragma", "no-cache"); headers.add("Expires", "0"); return ResponseEntity.ok() .headers(headers) .contentLength(file.length()) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(resource); } ``` 该方法首先创建一个文件对象,然后将文件的内容转换成字节流。之后使用ResponseEntity对象返回文件内容,同时设置HTTP头信息,将要下载文件名和类型等信息传递给客户端。 2.前端代码实现 在Vue中,可以使用Axios工具来调用后端的接口,并向接口传递需要下载文件名等参数。下面是一个简单的示例: ``` <template> <button @click="downloadFile">下载文件</button> </template> <script> import axios from 'axios'; export default { name: 'DownloadFileButton', methods: { downloadFile() { axios.get('/download?fileName=example.txt', { responseType: 'blob' }) .then(response => { const url = window.URL.createObjectURL(new Blob([response.data])); const link = document.createElement('a'); link.href = url; link.setAttribute('download', 'example.txt'); document.body.appendChild(link); link.click(); document.body.removeChild(link); }) .catch(error => { console.log(error); }) } } } </script> ``` 该示例中,当用户点击“下载文件”按钮时,会调用downloadFile方法。这个方法向服务器发送HTTP请求,请求下载名为“example.txt”的文件。Axios请求的responseType设为‘blob’,以确保服务器返回的数据可以正确处理。接着,在成功处理响应数据后,将响应数据构造成Blob对象并生成一个下载链接,通过设置HTML元素的属性来触发下载操作。 3.总结 通过以上步骤,我们可以实现Spring Boot Vue文件下载的功能。在后端代码中,需要提供文件下载的接口,并在返回的HTTP头信息中添加下载文件文件名、文件类型等信息。在前端代码中,需要使用Axios向后端发送请求,并实现下载文件的功能。同时,为了确保下载链接能够被正确处理,需要将响应数据构造成Blob对象。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值