SpringBoot实现文件下载

在写java 的文件下载的时候一直抛出异常

getOutputStream() has already been called for this response

抛出异常getOutputStream() has already been called for this response

直到使用了下面的方法:

 /**
     * 稿源周报excel表格下载
     * @return
     */

    @RequestMapping(value = "/downExcel", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String downExcel(HttpServletResponse response) throws UnsupportedEncodingException {
        LocalDate end = LocalDate.now();
        LocalDate start = end.minusDays(14);
        String filename = "稿源抓取周报-" + end.format(DateTimeFormatter.ISO_DATE) + ".xlsx";
        String filepath = "files/" + filename;
        writeExcelFile(start, end, filepath);
        // 如果文件名不为空,则进行下载
        if (filename != null) {
            File file = new File(filepath);
            // 如果文件存在,则进行下载
            if (file.exists()) {
                // 配置文件下载
                response.setHeader("content-type", "application/octet-stream");
                response.setContentType("application/octet-stream");
                // 下载文件能正常显示中文
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
                // 实现文件下载
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    System.out.println("Download  successfully!");
                    return "successfully";

                } catch (Exception e) {
                    System.out.println("Download  failed!");
                    return "failed";

                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return "";
    }

后来又出现了 一个问题就是后台不抛出异常,也不出现下载的提示发现了以下问题
 如果要用ajax 发送的话,则浏览器没有任何反应  因为ajax返回的格式是  字符的格式 

  $.ajax({
       url:"/down/downExcel",
       type:"GET",
       dataType:"json",
       success:function(result){
}}); 

换成:

window.location.href="/down/downExcel";

OK!

  • 15
    点赞
  • 59
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 13
    评论
在Spring Boot中实现文件下载可以通过以下步骤进行: 1. 首先,确保你的Spring Boot项目中添加了`spring-boot-starter-web`依赖。 2. 创建一个Controller类,用于处理文件下载请求。可以使用`@RestController`注解标记该类,并使用`@GetMapping`注解配置下载接口的URL路径。 3. 在下载接口方法中,使用`@PathVariable`注解来接收文件名作为参数。 4. 使用`ClassPathResource`类加载需要下载文件。你可以通过指定文件路径或者通过相对于classpath的路径来加载文件,取决于你的项目结构。 5. 使用`HttpServletResponse`对象设置相关的响应头信息,如Content-Type、Content-Disposition等,以确保文件以附件形式下载。 6. 使用`FileCopyUtils`类的`copy()`方法将文件内容写入到response的输出流中。 以下是一个简单的示例代码: ```java import org.springframework.core.io.ClassPathResource; import org.springframework.util.FileCopyUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; @RestController public class FileDownloadController { @GetMapping("/download/{fileName}") public void downloadFile(@PathVariable String fileName, HttpServletResponse response) throws IOException { ClassPathResource resource = new ClassPathResource("path/to/files/" + fileName); if (resource.exists()) { response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); InputStream inputStream = resource.getInputStream(); FileCopyUtils.copy(inputStream, response.getOutputStream()); inputStream.close(); } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); } } } ``` 请注意,上述代码中的`path/to/files/`应该根据你的实际文件路径进行替换。这个路径是相对于classpath的路径,因此可以根据你的项目结构进行调整。 这样,当访问`/download/{fileName}`时,就会触发文件下载操作,并将指定的文件作为附件下载到客户端。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhangvalue

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值