zoukankan      html  css  js  c++  java
  • Spring Boot 文件下载

    1. 文件下载类

    import javax.servlet.http.HttpServletResponse;
    import java.io.*;
    
    public class DownloadUtil {
    
        public boolean fileDownload(HttpServletResponse response,String filePath,String fileName)
            throws UnsupportedEncodingException {
            
            File file = new File(filePath);//创建下载的目标文件,参数为文件的真实路径
            if(file.exists()){ //判断文件是否存在
                response.setContentType("application/vnd.ms-excel;charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                response.setHeader("Content-Disposition", "attachment;fileName=" +   java.net.URLEncoder.encode(fileName,"UTF-8"));
                byte[] buffer = new byte[1024];
                FileInputStream fis = null; //文件输入流
                BufferedInputStream bis = null;
    
                OutputStream os = null; //输出流
                try {
                    os = response.getOutputStream();
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    int i = bis.read(buffer);
                    while(i != -1){
                        os.write(buffer);
                        i = bis.read(buffer);
                    }
    
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
                try {
                    bis.close();
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    return false;
                }
            }
            return true;
        }

    2. 文件下载a标签

    <a th:href="@{/download/} + ${fileName}+'?filePath='+${filePath}">点击下载文件</a>

    filePath为文件的真实路径,由于路径的符号与RESTful API风格冲突,所以采取传统a标签的传参方式

    3. 控制器

    /**
         * 测试文件下载
         * @param fileName
         * @param filePath
         * @param response
         * @return
         * @throws UnsupportedEncodingException
         */
    @GetMapping("/download/{fileName}")
    public String testDownload(@PathVariable("fileName") String fileName,String filePath,HttpServletResponse response) throws UnsupportedEncodingException {
    
        System.out.println("==>开始文件下载!");
    
        DownloadUtil downloadUtil = new DownloadUtil();
    
        downloadUtil.fileDownload(response,filePath,fileName);
    
        return null;
    }
  • 相关阅读:
    [iOS基础控件
    [iOS基础控件
    后端程序员必会常用Linux命令总结
    MySQL数据库SQL语句基本操作
    MySQL拓展操作
    http/1.0/1.1/2.0与https的比较
    http中的socket是怎么一回事
    Django content_type 简介及其应用
    WEB主流框架技术(汇聚页)
    WEB基础技术(汇聚页)
  • 原文地址:https://www.cnblogs.com/lcsin/p/11705084.html
Copyright © 2011-2022 走看看