这里实现的下载程序包中指定路径的文件,我们将指定文件存放在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();
}
}
}
来源:CSDN
作者:Gordon家的哈士奇
链接:https://blog.csdn.net/qq_36743013/article/details/103990632