你知道springmvc要怎样才能够从服务器下载文件吗?很多人对于这个方法都不大了解,那么下面就一起通过实例来学习一下吧。
注意:使用response方式下载文件,不可以使用ajax请求,否则的话就会无反应。
@RequestMapping(value = "exportExcel") public void exportExcle(HttpServletRequest request, HttpServletResponse response) throws Exception { String realPath = request.getSession() .getServletContext() .getRealPath("/"); File filePath = new File(realPath + "/tempExclePath"); String path = filePath + "/" + key + ".xlsx"; final File file = new File(path); fileName = file.getName(); InputStream inputStream; try { inputStream = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[inputStream.available()]; inputStream.read(buffer); inputStream.close(); response.reset(); response.addHeader("Content-Disposition", "attachment;filename=" + fileName); response.addHeader("Content-Length", "" + file.length()); OutputStream os = new BufferedOutputStream(response.getOutputStream()); response.setContentType("application/octet-stream"); os.write(buffer); os.flush(); os.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (file.exists()) { // after download, delete the file on server (new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } finally { try { file.delete(); } catch (Exception e) {} } } })) .start(); } } }
以上就是对于springmvc如何从服务器下载文件的简单介绍了,希望可以对你有所帮助,更多和springmvc相关的知识,请继续关注奇Q工具网的java架构师栏目来了解吧。
推荐阅读: