• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

SpringBoot中文件下载的两种方法

java实例 海叔叔 4年前 (2021-10-17) 101次浏览 已收录 0个评论

SpringBoot中文件下载的两种方法

第一种:文件已存在于服务器上

可能是图片,视频等资源文件

import java.io.*;
import java.net.URLEncoder;
import java.util.*;
 
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
 
import javax.servlet.http.HttpServletResponse;
 
@RestController
public class Controller {
 
    @GetMapping(value = "/downloadFile", consumes = MediaType.ALL_VALUE)
    void downloadFile(final HttpServletResponse response)
            throws Exception {
 
        // 获取文件
        File file = new File("Z:/wallpapers/1/wallhaven-839kvo你好.jpg");
        //文件名
        String fileName = file.getName();
 
        // 清空缓冲区,状态码和响应头(headers)
        response.reset();
        // 设置ContentType,响应内容为二进制数据流,编码为utf-8,此处设定的编码是文件内容的编码
        response.setContentType("application/octet-stream;charset=utf-8");
        // 以(Content-Disposition: attachment; filename="filename.jpg")格式设定默认文件名,设定utf编码,此处的编码是文件名的编码,使能正确显示中文文件名
        response.setHeader("Content-Disposition", "attachment;fileName="+ fileName +";filename*=utf-8''"+URLEncoder.encode(fileName,"utf-8"));
 
        // 实现文件下载
        byte[] buffer = new byte[1024];
        FileInputStream fis = null;
        BufferedInputStream bis = null;
        try {
            fis = new FileInputStream(file);
            bis = new BufferedInputStream(fis);
            // 获取字节流
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            System.out.println("Download successfully!");
        }
        catch (Exception e) {
            System.out.println("Download failed!");
        }
        finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

第二种:创建文件数据并下载

这种情况多为文档,例如excel,建议使用easyexcel


import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.List;
 
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
 
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
 
import javax.servlet.http.HttpServletResponse;
 
@RestController
public class Controller {
 
    @GetMapping(value = "/downloadExcel", consumes = MediaType.ALL_VALUE)
    void downloadExcel(final HttpServletResponse response)
            throws Exception {
 
        String name = "测试." + ExcelTypeEnum.XLSX;
        // 清空缓冲区,状态码和响应头(headers)
        response.reset();
        // 设置ContentType,响应内容为文本数据,编码为utf-8,此处设定的编码是文件内容的编码
        response.setContentType("text/plain;charset=utf-8");
        // 以(Content-Disposition: attachment; filename="filename.jpg")格式设定默认文件名,设定utf编码,此处的编码是文件名的编码,使能正确显示中文文件名
        response.setHeader("Content-Disposition", "attachment;fileName=" + name + ";filename*=utf-8''" + URLEncoder.encode(name, "utf-8"));
 
        // 响应输出流
        OutputStream out = response.getOutputStream();
        // 建立excel
        ExcelWriter excelWriter = EasyExcel.write(out).build();
        // 建立sheet
        WriteSheet writeSheet = EasyExcel.writerSheet("sheet1").build();
        // 指定sheet并写数据
        excelWriter.write(getListString(), writeSheet);
        // 不要忘记
        excelWriter.finish();
        out.flush();
    }
 
    // 生成excel内容
    List<List<String>> getListString() {
        List<List<String>> result = new LinkedList<>();
        List<String> data1 = new LinkedList<>();
        data1.add("1");data1.add("张三");data1.add("北京");
        result.add(data1);
        List<String> data2 = new LinkedList<>();
        data2.add("2");data2.add("李四");data2.add("上海");
        result.add(data2);
        List<String> data3 = new LinkedList<>();
        data3.add("3");data3.add("王五");data3.add("广州");
        result.add(data3);
        return result;
    }
}

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:SpringBoot中文件下载的两种方法
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址