Springboot下载程序包中的文件

2 篇文章 0 订阅

这里实现的下载程序包中指定路径的文件,我们将指定文件存放在resources的static文件夹下面。前台就是代码请求后台不要使用ajax请求,因为下载文件不支持ajax请求,可以使用window.location.href="#"或者是document.getElementById("downFrame").src=具体地址。看下后台代码。

之前遇到过问题是在idea下是可以成功下载的,但是部署在Linux环境下就不能够下载了。现在解决了这个问题。使其在Windows和Linux环境都可以用。大致代码如下:

public void test(HttpServletRequest request, HttpServletResponse response) throws Exception{
    String fileName = "c.zip";
    String filePath = "static" + File.separator + fileName;
    ClassPathResource re = new ClassPathResource(filePath);
    response.setContentType("application/vnd.ms-excel");
    response.setHeader("Content-Disposition","filename="+new String(fileName.getBytes("GBK"),"ISO-8859-1"));
    response.setHeader("Pragma","No-cache");
    OutputStream os = response.getOutputStream();
    InputStream fis = re.getInputStream();
    try {
        byte[] data = new byte[1024];
        int size = du(fis, data);
        while (size != -1) {
            outWrite(os, data, 0, data.length);
        }
        os.flush();
    }catch(Exception e) {
        response.reset();
        e.printStackTrace();
    }finally {
        fis.close();
        os.close();
        response.flushBuffer();
    }

}


public static int du(InputStream in, byte buffer[]) {
    int readSize = 0;
    try {
        readSize = in.read(buffer);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return readSize;
}


public static void outWrite(OutputStream out, byte buffer[], int start, int readSize) {
    if (out != null && buffer.length > 0) {
        try {
            out.write(buffer, start, readSize);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();

        }
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值