Springboot下载程序包中的文件

Deadly 提交于 2020-01-16 02:29:26

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

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

String fileName = "c.zip"

String filePath = "static"+File.separator+fileName;

ClassPathResource re = new ClassPathResource(filePath);

response.setContentType("application/vnd.ms-excel");

response.setHeader("Content-Dispostion","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 = SecurityUtil.du(fis,data);

     while(size != -1){

SecurityUtil.outWrite(os,data,0,data.length);

}

os.flush();

}catch(Exceptiion){

response.reset();

e.printStackTrace();

}finally{

fis.close();

os.close();

response.flushBuffer();

}

 

public static int du(InputStream in,byte buffer[]){

int readSize = 0;

try{

readSzie = in.read(buffer);

}catch(IOException e){

e.printStackTrace();

}

}

 

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();

}

}

}

 

 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!