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!

SpringBoot实现文件下载_第1张图片

你可能感兴趣的:(Java)