Springboot文件下载工具类

这篇具有很好参考价值的文章主要介绍了Springboot文件下载工具类。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

package com.synda.utils;

import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class DownloadUtil {
    private static final Logger log = LoggerFactory.getLogger(DownloadUtil.class);

    public static void downloadFileByPath(HttpServletResponse response,String filePath,boolean isOnLine){
        setResponse(response,null,filePath,"","",isOnLine);
        download(response,new File(filePath));
    }

    /**
     * 根据文件路径下载文件
     * @param response 相应体
     * @param filePath 文件路径
     * @param contentType 文件类型
     */
    public static void downloadFileByPath(HttpServletResponse response,String filePath,String contentType,boolean isOnLine){
        setResponse(response,null,filePath,contentType,"",isOnLine);
        download(response,new File(filePath));
    }


    /**
     * 根据文件路径下载文件
     * 指定文件名
     * @param response 相应体
     * @param filePath 文件路径
     * @param contentType 文件类型
     * @param fileName 文件名
     */
    public static void downloadFileByPath(HttpServletResponse response,String filePath,String contentType,String fileName,boolean isOnLine){
        setResponse(response,null,filePath,contentType,fileName,isOnLine);
        download(response,new File(filePath));
    }

    /**
     * 下载文件
     * @param response 相应体
     * @param file 文件路径
     */
    public static void downloadFile(HttpServletResponse response,File file){
        setResponse(response,file,"","","",false);
        download(response,file);
    }

    /**
     * 下载文件
     * @param response 相应体
     * @param file 文件路径
     * @param contentType 文件类型
     */
    public static void downloadFile(HttpServletResponse response,File file,String contentType,boolean isOnLine){
        setResponse(response,file,"",contentType,"",isOnLine);
        download(response,file);
    }


    /**
     * 下载文件 指定文件名
     * @param response 相应体
     * @param file 文件
     * @param contentType 文件类型
     */
    public static void downloadFile(HttpServletResponse response,File file,String contentType,String fileName,boolean isOnLine){
        setResponse(response,file,"",contentType,fileName,isOnLine);
        download(response,file);
    }

    /**
     * 下载文件 指定文件名
     * @param response 相应体
     * @param inputStream 文件
     * @param contentType 文件类型
     */
    public static void downloadFileByStream(HttpServletResponse response,FileInputStream inputStream,String contentType,String fileName,boolean isOnLine){
        setResponse(response,contentType,fileName,isOnLine);
        download(response,inputStream);
    }

    /**
     * 下载文件 指定文件名
     * @param response 相应体
     * @param data 文件字节
     * @param contentType 文件类型
     */
    public static void downloadFileByByte(HttpServletResponse response,byte[] data,String contentType,String fileName,boolean isOnLine){
        setResponse(response,contentType,fileName,isOnLine);
        download(response,data);
    }



    /**
     * 设置请求头
     * @param response 相应对象
     * @param file 文件,如果不传,则使用文件路径加载
     * @param filePath 文件路径
     * @param contentType 文件头
     * @param fileName 文件名称
     */
    private static void setResponse(HttpServletResponse response,File file,String filePath,String contentType,String fileName,boolean isOnLine){
        if (file==null) file = new File(filePath);
        fileName = StringUtils.hasText(fileName) ? fileName: file.getName();
        setResponse(response,contentType,fileName,isOnLine);
    }

    /**
     * 设置请求头
     * @param response 相应对象
     * @param contentType 文件头
     * @param fileName 文件名称
     */
    private static void setResponse(HttpServletResponse response,String contentType,String fileName,boolean isOnLine){
        contentType = StringUtils.hasText(contentType) ? contentType: "application/octet-stream";
        response.setCharacterEncoding("UTF-8");
        response.setContentType(contentType);
        if (isOnLine){
            response.setHeader("Content-Disposition", "inline; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        }else {
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        }
    }

    private static void download(HttpServletResponse response,File file){
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            download(response,fileInputStream);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    private static void download(HttpServletResponse response,byte[] data){
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
        download(response,byteArrayInputStream);
    }

    /** 文件下载工具类 */
    private static void download(HttpServletResponse response,InputStream inputStream){
        byte[] buffer = new byte[1024];
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(inputStream);
            response.setHeader("Content-Length", String.valueOf(inputStream.available())); // 内容长度
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            log.info("File download successfully!");
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.info("File download failed !");
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

文章来源地址https://www.toymoban.com/news/detail-563823.html

到了这里,关于Springboot文件下载工具类的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 如何下载github上用git-lfs工具下载的大文件

    要下载 GitHub 上使用 Git LFS 工具存储的大文件,您可以进行以下步骤: 安装 Git LFS:如果您的系统上没有安装 Git LFS,请先安装它。可以通过终端或命令行进行安装。 克隆存储库:使用以下命令克隆项目存储库到本地: 下载大文件:进入存储库目录,并使用以下命令下载大文

    2024年02月12日
    浏览(47)
  • 调用hutool包调用http接口处理文件流-文件的上传下载工具类

    hutool工具类get请求获取流: InputStream inputStream = HttpRequest.get(fileUrl).execute().bodyStream(); hutool工具类post请求上传文件流: String resp = HttpRequest.post(url).header(Header.CONTENT_TYPE.getValue(), ContentType.MULTIPART.getValue()).form(params).execute().body(); 完成代码

    2024年01月17日
    浏览(43)
  • 使用hutool工具,对多文件下载进行打包下载,这里使用的是zip压缩算法。

    参考以下博主: Java实现文件下载zip包单文件等_java下载zip文件_liu.kai的博客-CSDN博客 先将需要压缩的文件们打包在一块生成一个临时压缩包 将这个临时的压缩包,以单文件下载的方式,给前端响应过去 删除临时的压缩包

    2024年02月04日
    浏览(69)
  • 使用hutool工具(ZipUtil)对多文件打包压缩并通过浏览器下载

    使用hutool工具对多文件进行打包压缩并下载 需求 工作中遇到需要将详情页面数据导出为word,同时详情中有图片和附件,由于附件没法写入到word中(可能是自己没有找到对应的解决办法) , 故将需要导出的word文件,和附件一同打包成zip,进行下载 实现 共两个步骤 1 . 使用hutool对多文

    2024年02月12日
    浏览(30)
  • Linux安装ossutil工具且在Jenkins中执行shell脚本下载文件

    测试中遇到想通过Jenkins下载OSS桶上的文件,要先在linux上安装ossutil工具,记录安装过程如下: 一、下载安装ossutil,使用命令 1.下载:wget https://gosspublic.alicdn.com/ossutil/1.7.13/ossutil64 2.一定要赋权限:chmod 755 ossutil64,不然会提示权限不足 3.配置文件: ./ossutil64 config 输入accessK

    2024年01月19日
    浏览(32)
  • JAVA使用POI对Word docx模板文件替换数据工具类并通过浏览器下载到本地

    需求:需要上传一个带有占位符的模板至数据库保存,然后解析模板的占位符,通过类计算结果替换模板中的占位符,并且保存至本地 难点:1.由于我数据库保存是本地保存,并没有path 所以获取模板的path是个难点 2.如何使用计算类,由于我的类是和占位符绑定的,什么样的

    2024年02月16日
    浏览(35)
  • springboot 发送邮件,以及邮件工具类 并且解决spring-boot-starter-mail 发送邮件附件乱码或者文件错乱

    1、设置系统值 System.setProperty(“mail.mime.splitlongparameters”, “false”); 2、 在创建对象的时候定义编码格式(utf-8): MimeMessageHelper helper = new MimeMessageHelper(mes, true, “utf-8”); 3、 其次,在添加附件的时候,附件名是需要定义编码的 helper.addAttachment(MimeUtility.encodeWord(附件名,“utf-8”

    2024年02月15日
    浏览(45)
  • 中文编程工具免费版下载,中文开发语言工具免费版下载

    中文编程工具免费版下载,中文开发语言工具免费版下载 中文编程工具开发的实际部分案例如下图 编程系统化课程总目录及明细,点击进入了解详情。https://blog.csdn.net/qq_29129627/article/details/134073098?spm=1001.2014.3001.5502

    2024年02月08日
    浏览(51)
  • BT下载磁力下载工具,这几款,不限速

    想看个电影,迅雷限速,经常还因为某些原因下不了,下载电影,BT下载工具总少不了,今天给大家推荐这几款BT下载磁力链接下载工具。不限速下载,超爽! 一、Motrix Motrix是一款全能的下载工具,支持下载 HTTP、FTP、BT、磁力链、百度网盘等资源。Motrix使用aria2作为内核,下

    2024年02月13日
    浏览(47)
  • SpringBoot + Vue前后端分离项目实战 || 三:Spring Boot后端与Vue前端连接

    系列文章: SpringBoot + Vue前后端分离项目实战 || 一:Vue前端设计 SpringBoot + Vue前后端分离项目实战 || 二:Spring Boot后端与数据库连接 SpringBoot + Vue前后端分离项目实战 || 三:Spring Boot后端与Vue前端连接 SpringBoot + Vue前后端分离项目实战 || 四:用户管理功能实现 SpringBoot + Vue前后

    2024年02月12日
    浏览(55)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包