IO(3) : 文件下载

 参考 :

    https://blog.csdn.net/qq_31940707/article/details/80405218

    https://www.cnblogs.com/sunny3096/p/8204291.html

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * @Auther: liyue
 * @Date: 2018/11/15 16:39
 * @Description:
 */
@RestController
@RequestMapping("/download")
public class DownloadConroller {

    @RequestMapping("/download_excel")
    public void downloadExcel(String fileName, HttpServletResponse response) {
        // 2.获取要下载的文件的绝对路径
        File file = new File(fileName);
        try {
            // 3.设置content-disposition响应头控制浏览器以下载的形式打开文件
            // 设置强制下载不打开
            response.setContentType("application/force-download");
            // 设置文件名
            response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "utf-8"));
            // 4.根据文件路径获取要下载的文件输入流
            InputStream in = new FileInputStream(file);
            int len = 0;
            // 5.创建数据缓冲区
            byte[] buffer = new byte[1024];
            // 6.通过response对象获取OutputStream流
            OutputStream out = response.getOutputStream();
            // 7.将FileInputStream流写入到buffer缓冲区
            while ((len = in.read(buffer)) > 0) {
                // 8.使用OutputStream将缓冲区的数据输出到客户端浏览器
                out.write(buffer, 0, len);
            }
            in.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值