Java Springboot 下载文件

Java  springboot 控制类 

@RequestMapping(value = "downloadFile", method = RequestMethod.GET)
	@ResponseBody
	public void downloadFile( HttpServletResponse resp, String filename){
		String downloadName = filename + ".apk";
		downloadFileTool.download(resp, filename, downloadName);

	}

Java   新建 downloadFileTool

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletResponse;

public class downloadFileTool {

	    /**
	     * @param resp
	     * @param name         文件真实名字
	     * @param downloadName 文件下载时名字
	     */
	    public static void download(HttpServletResponse resp, String name, String downloadName) {
	        String fileName = null;
	        try {
	            fileName = new String(downloadName.getBytes("GBK"), "ISO-8859-1");
	        } catch (UnsupportedEncodingException e) {
	            e.printStackTrace();
	        }

	        String path ="D:\\mtapp\\"+name+".apk";
	        File file = new File(path);
	        resp.reset();
	        resp.setContentType("application/octet-stream");
	        resp.setCharacterEncoding("utf-8");
	        resp.setContentLength((int) file.length());
	        resp.setHeader("Content-Disposition", "attachment;filename=" + fileName);
	        byte[] buff = new byte[1024];
	        BufferedInputStream bis = null;
	        OutputStream os = null;
	        try {
	            os = resp.getOutputStream();
	            bis = new BufferedInputStream(new FileInputStream(file));
	            int i = 0;
	            while ((i = bis.read(buff)) != -1) {
	                os.write(buff, 0, i);
	                os.flush();
	            }
	        } catch (IOException e) {
	            e.printStackTrace();
	        } finally {
	            try {
	                bis.close();
	            } catch (IOException e) {
	                e.printStackTrace();
	            }
	        }
	    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值