文件下载

1、以上一篇文章jxsl导出Excel为实例,在导出Excel之后,客户端需要直接将导出的Excel下载到本地,因为导出之后实际上该Excel还是保持在服务器端的,所以还有一个下载的过程,以数据流的形式完成下载工作。工具类JxlsExportExcel.java代码如下:

package com.inmansoft.base.util;

import lombok.extern.slf4j.Slf4j;
import org.jxls.common.Context;
import org.jxls.transform.poi.PoiContext;
import org.jxls.util.JxlsHelper;
import org.springframework.util.FileCopyUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

@Slf4j
public class JxlsExportExcel {

    private static String output =  "export_leadshow.xls";

    public static void excute(Map map,HttpServletResponse response) throws IOException {
     //springboot打包成jar之后识别不来其他磁盘路径,只能通过这种形式将导出的Excel文件保存到项目路径下 String filePath
= System.getProperty("user.dir") + "/" + output; try (InputStream is = JxlsExportExcel.class.getResourceAsStream(map.get("templates").toString())) { try (OutputStream os = new FileOutputStream(filePath)) { Context context = new PoiContext(); context.putVar("object", map.get("list")); JxlsHelper.getInstance().processTemplate(is, os, context); //下载 response.setHeader("Content-type","text/html;charset=UTF-8");//这里需要注意,之前试了很多,都乱码了,另外用swagger的同学请注意一下,最好是直接通过前端代码调用接口的形式测试 response.setHeader("Content-Disposition", "attachment;filename=" + output);//由于现在导出的文件名为中文,所以没有做乱码处理,若文件名带有中文,需做乱码处理 InputStream in = new FileInputStream(filePath); OutputStream outputStream = response.getOutputStream(); FileCopyUtils.copy(in, outputStream); outputStream.flush(); outputStream.close(); //删除 File file = new File(filePath); file.delete(); } } } public static void download(String fileName, HttpServletResponse response) throws UnsupportedEncodingException { String path = System.getProperty("user.dir"); if (fileName != null) { //设置文件路径 File file = new File(path + "/" + fileName); if (file.exists()) { response.setHeader("Content-type","text/html;charset=UTF-8"); response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.split("/")[1].getBytes("gbk"))); try (FileInputStream fileInputStream = new FileInputStream(file)) { OutputStream outputStream = response.getOutputStream(); FileCopyUtils.copy(fileInputStream, outputStream); outputStream.flush(); outputStream.close(); } catch (Exception e) { e.printStackTrace(); log.error("download error, file:" + fileName, e); } } } } }

2、控制层代码ApartBomController.java如下所示:

@ApiOperation(value = "jxsl导出Excel", notes = "jxsl导出Excel")
    @GetMapping("/jxslExport/{rootId}")
    public void jxslExport(@PathVariable("rootId") String rootId,HttpServletResponse response) throws IOException {
        List<ApartBom> list = apartBomService.getTreeList(rootId);
        List<ApartBom> newList = new ArrayList<>();
        for (ApartBom ab : list) {
            methodOne(ab);
            List<ApartBom> list1 = ab.getChildren();
            newList.add(ab);
            if (list1 != null) {
                for (ApartBom ab1 : list1) {
                    methodOne(ab1);
                    newList.add(ab1);
                }
            }
        }
        Map map = new HashMap();
        map.put("templates",template);
        map.put("list",newList);
        JxlsExportExcel.excute(map,response);
    }

 3、前端调用这个API的时候切记不要用ajax调用,因为ajax请求只是个“字符型”的请求,即请求的内容是以文本类型存放的。文件的下载是以二进制形式进行的,虽然可以读取到返回的response,但只是读取而已,是无法执行的。直接用window.location.href = url,这样可完成下载。

原文地址:https://www.cnblogs.com/Crysta1/p/10250404.html