文件下载

package com.spiov.cloud.sys.util;

import org.apache.commons.io.FileUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;

public class DownloadUtil {

    /**
     * @description: 文件下载
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     * @date: 2019/8/12 14:03
     * @return: void
     */
    public static void downloadTemplate(HttpServletRequest request, HttpServletResponse response) throws Exception{
        final String fileName = "xxx.xls";
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream("file/" + fileName);
        if(inputStream != null){
            //解决项目打成jar包之后,下载的文件损坏(POI是专业的,对于Excel文件处理)
            Workbook workbook = WorkbookFactory.create(inputStream);
            response.setCharacterEncoding("UTF-8");
            //设置Content-Type头
            response.setContentType("application/octet-stream;charset=UTF-8");
            //设置Content-Disposition头 以附件形式解析
            String encodedFileName = getEncodedFilename(request, fileName);
            response.addHeader("Content-Disposition", "attachment;filename=" + encodedFileName);
            ServletOutputStream outputStream = null;
            try {
                outputStream = response.getOutputStream();
                workbook.write(outputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                //流的关闭
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (outputStream != null) {
                    try {
                        outputStream.flush();
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * @Description 文件下载
     * @Param [fileName, file, request]
     * @Date 16:57 2019/7/1
     * @return org.springframework.http.ResponseEntity<byte[]>
     **/
    public static ResponseEntity<byte[]> downloadFile(String fileName, File file, HttpServletRequest request) throws Exception {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        String encodeName = getEncodedFilename(request,fileName);
        headers.add("Content-Disposition", "attachment; filename=" + encodeName);
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Last-Modified", new Date().toString());
        headers.add("ETag", String.valueOf(System.currentTimeMillis()));
        headers.setContentType(MediaType.parseMediaType("application/vnd.ms-excel"));
        headers.setContentLength(file.length());
        return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
    }





    /**
     * @Description 获取URL编码后的原始文件名
     * @Param [request, fileName]
     * @Date 16:40 2019/7/1
     * @return java.lang.String
     **/
    private static String getEncodedFilename(HttpServletRequest request, String fileName) throws Exception {
        String encodedFileName;
        String agent = request.getHeader("USER-AGENT").toLowerCase();
        if(agent.contains("Firefox")){
            //火狐浏览器
            encodedFileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        }else{
            //其他浏览器
            encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
        }
        return encodedFileName;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值