文件下载的主要思路是前台触发form的post请求,后台将文件获取后写入输出流中。
1、前台定义form表单
<form id="downForm" method="post"> <input type="hidden" id="filepath" name="filepath" value=""> <input type="hidden" id="filename" name="filename" value=""> </form>
2、后台定义相关触发方法
function downForm(fileName,filePath){ $("#downForm").attr("action","/demand/down"); $("#filepath").val(filePath); $("#filename").val(fileName); $("#downForm").submit(); }
3、后台接收参数
public void down(HttpServletRequest request,HttpServletResponse response){ request.setAttribute("filePath", request.getParameter("filepath")); request.setAttribute("fileName", request.getParameter("filename")); try { fileService.fileDownlaod(request,response, true); } catch (Exception e) { System.out.println(e.getMessage()); } }
4、实现写入操作
public void fileDownlaod(HttpServletRequest request,HttpServletResponse response, boolean isOnLine) throws Exception{ String filepath = (String) request.getAttribute("filePath"); String filename = (String) request.getAttribute("fileName"); File f = new File(filepath); if (!f.exists()) { throw new GlobalException("文件不存在"); } response.reset(); // 非常重要 if (isOnLine) { // 在线打开方式 URL u = new URL("file:///" + filepath); response.setContentType(u.openConnection().getContentType()); response.setHeader("Content-Disposition", "inline; filename=" + f.getName()); } else { // 纯下载方式 response.setContentType("application/x-msdownload"); response.setHeader("Content-Disposition", "attachment; filename=" + new String(filename.getBytes("gb2312"), "iso-8859-1")); } OutputStream out = response.getOutputStream(); BufferedInputStream br = new BufferedInputStream(new FileInputStream(f)); byte[] buf = new byte[1024]; int len = 0; while ((len = br.read(buf)) > 0){ out.write(buf, 0, len); } br.close(); out.close(); }