Springboot实现文件下载的方式
作者:mmseoamin日期:2023-12-13

方式一:返回的数据写入响应流以文件方式下载

		StringBuilder content = new StringBuilder();
        OutputStream outputStream = null;
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + logId + ".log");
            response.setHeader("Content-Type", "application/octet-stream");
            response.setContentType("application/octet-stream; charset=UTF-8");
            outputStream = response.getOutputStream();
            outputStream.write(content.toString().getBytes());
            outputStream.flush();
        } catch (Exception e) {
            // ignored
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

方式二:某个位置的文件下载

        InputStream inputStream = null;
        OutputStream outputStream = null;
        HttpServletResponse response = HttpServletUtil.getResponse();
        try{
            response.setHeader("Content-Disposition", "attachment;filename=" + logId + ".log");
            response.setHeader("Content-Type", "application/octet-stream");
            response.setContentType("application/octet-stream; charset=UTF-8");
            inputStream = Files.newInputStream(new File("文件路径").toPath());
            outputStream = response.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            //从输入流中读取一定数量的字节,并将其存储在缓冲区字节数组中,读到末尾返回-1
            while ((len = inputStream.read(b)) > 0) {
                outputStream.write(b, 0, len);
            }
        }catch(Exception e){
            // ignored
        }finally {
            try{
                if (inputStream != null) inputStream.close();
                if (outputStream != null) outputStream.close();
            }catch(Exception e){
                // ignored
            }
        }

===>工具类

package com.wisesoft.common.util;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * ClassName: com.wisesoft.xodb.common.util.HttpServletUtil
 * Name:HttpServletUtil
 * Author: xiong-feng
 * Date: 2021/12/9 8:54
 * Description: 获取http信息
 */
public class HttpServletUtil {
    /**
    * Description:  获取request请求域
    * Author: xiong-feng
    * Date: 2021/12/9
    */
    public static HttpServletRequest getRequest(){
        return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
    }
    /**
    * Description:  获取response响应域
    * Author: xiong-feng
    * Date: 2021/12/9
    */
    public static HttpServletResponse getResponse(){
        return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getResponse();
    }
}