//JS
filedownLoad:function(id){
downForm = $("#fileForm").form(); downForm.form('submit', { url : ctx+'/file/downLoad.shtml?fileid='+id, type : 'POST', success : function(data) { if(!data.flag){ layer.msg("资源不存在!"); } } })}
//JSP页面
<div class="file-name"> ${item.file_name} <br> <form id="fileForm" method="post"> <input type="hidden" id="fileid" name="file_id" value="${item.file_id}"/> </form> <small>上传时间:<fmt:formatDate value="${item.upload_time}" pattern="yyyy-MM-dd"/><a href="javascript:void(0)" οnclick="fileview.filedownLoad(${item.file_id});" style="margin-left: 40px;font-size:14px; color: #676a6c;" ><i class="glyphicon glyphicon-cloud-download"></i> </a></small> </div>
//控制层
@RequestMapping(value = "/downLoad") public void downLoad( HttpServletResponse response,Integer fileid,PrintWriter writer) throws Exception { JSONObject result = new JSONObject(); Map<String, Object> map = new HashMap<String, Object>(); map.put("file_id", fileid); List<SpFile> filelist = spFileService.selectSpfileByObjectid(map); String hostpath = SysConfigManager.getInstance().getText("/config/system/file"); String path = hostpath+filelist.get(0).getPath(); File f = new File(path); if (!f.exists()) { result.put("flag", false); response.setContentType("text/html;charset=utf-8"); writer.println(result); }else{ FileUtils.down(response, path,f.getName()); } }
//下载文件的方法
public static void down(HttpServletResponse response, String path, String filename) throws Exception { File downloadFile = new File(path); InputStream in = null; OutputStream out = null; try { response.reset(); response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8")); in = new FileInputStream(downloadFile); out = response.getOutputStream(); byte[] bytes = new byte[1024]; int length; while ((length = in.read(bytes, 0, bytes.length)) > -1) { out.write(bytes, 0, length); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { in.close(); out.flush(); out.close(); } }