这里实现的下载程序包中指定路径的文件,我们将指定文件存放在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(); } } }