这个下载方式是这么样的,可以适用于很多情况:
jsp页面点击某个按钮,实现下载;
jsp页面一加载完就下载;
演示一个一加载完就实现下载的:
实现跳转到另一个url上,
@RequestMapping(value="/{id}/down")public String down(@PathVariable long id,HttpServletRequest request,HttpServletResponse response){String rootPath= ...; File file = new File(rootPath);this.setResponse(response, request, null, rootPath);this.copyFileToResponse(response, file);return null;}
protected void setResponse(HttpServletResponse response, HttpServletRequest request, String mime, String fileName) {if (!Strings.isNullOrEmpty(mime)) {response.setContentType(mime);} else {response.setContentType("application/octet-stream;charset=ISO-8859-1");}if (!Strings.isNullOrEmpty(fileName)) {try {// 判断是否为IEif (request.getHeader("USER-AGENT").toLowerCase().indexOf("msie") > 0) {response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF8"));}else{response.setHeader("Content-disposition","attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso-8859-1"));}} catch (UnsupportedEncodingException e) {e.printStackTrace();}} else {response.setHeader("Content-Disposition", "attachment; filename=");}}
protected void copyFileToResponse(HttpServletResponse response, File file) {OutputStream to;try {to = response.getOutputStream();Files.copy(file, to);to.flush();response.flushBuffer();} catch (IOException e) {e.printStackTrace();}}