Java HttpServlet如何下载excel文件
我正在尝试添加一个函数到我的web应用程序,它允许用户下载一个excel文件。
我试图用下面的代码来实现这个:
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) { File file = new File("d:/test/test.xls"); response.setContentType("application/xls"); response.addHeader("Content-Disposition", "attachment; filename=test.xls"); response.setContentLength((int) file.length()); try { FileInputStream fileInputStream = new FileInputStream(file); OutputStream responseOutputStream = response.getOutputStream(); int bytes; while ((bytes = fileInputStream.read()) != -1) { responseOutputStream.write(bytes); } fileInputStream.close(); responseOutputStream.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
我可以用上面的代码下载excel文件,但是文件已损坏。 如果我用Microsoft Excel打开它,我会popup消息:
“文件格式和扩展名不匹配,文件可能被破坏或不安全”。
而Excel文件是空的。
运行代码后,原始文件(d:/test/test.xls)也被损坏。
我究竟做错了什么?
Excel文件.xls
的官方MIMEtypes是application/vnd.ms-excel
,而.xlsx
是application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
。
此外,我build议在写入输出stream和responseOutputStream.flush()
(重要)之前做response.reset()
,然后再closuresresponse
。
尝试下面的代码:
File file = null; InputStream in = null; OutputStream outstream = null; try { response.reset(); in = new FileInputStream(file); response.setContentType("application/vnd.ms-excel"); response.addHeader("content-disposition", "attachment; filename=data.xls"); outstream = response.getOutputStream(); IOUtils.copyLarge(in, outstream); } catch (Exception e) { out.write("Unable to download file"); }finally { IOUtils.closeQuietly(outstream); IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); if (file != null) file.delete(); }
不要忘了在你的依赖中添加apache commons-io-2.4