IO(8) : 文件下载

参考 : 使用SpringBoot实现文件的下载 - LonZyuan - 博客园 


import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${filePath:/home}")
    private String filePath;

    @GetMapping("/download/{fileName}")
    public void download(HttpServletResponse response, @PathVariable("fileName") String fileName) {
        try {
            File file = new File(filePath);
            String[] strings = filePath.split("/");
            response.addHeader("Content-Length", String.valueOf(file.length()));
            response.setHeader("content-type", fileName.split("[.]")[1]);
            response.setContentType("application/octet-stream");
            // 文件名中文乱码处理
            response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "utf-8"));
            byte[] buff = new byte[1024];
            //创建缓冲输入流
            try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
                 OutputStream outputStream = response.getOutputStream()) {
                //这个路径为待下载文件的路径
                int read = bis.read(buff);
                //通过while循环写入到指定了的文件夹中
                while (read != -1) {
                    outputStream.write(buff, 0, buff.length);
                    outputStream.flush();
                    read = bis.read(buff);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

END。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值