一.背景說明
現在我做的系統中,需要有一個下載附件的功能,其實就是下載圖片到本地中。相應的圖片保存在多媒體系統中,我們只能拿到它的資源地址(url),而不是真實的文件。
這里記錄的是下載單個圖片。下篇文章中有介紹批量下載(下一篇文章)。
二.代碼
1.html
/* * 下載選中的附件 */ $("#merchantApproval-annes-center-tb .downloadButton").click(function(){ //獲取選中的行,此行包含了附件的相關信息 var row = $("#merchantApproval-annes-center-dg").datagrid("getSelected"); if(row){ //獲取圖片的資源地址 var imgUrl = $("#imageDivId>img").attr("src"); //向后台發送請求,參數是imgUrl和imgName window.location="${ctx}/approvalImageHandle.do?method=downloadImage&imgUrl="+imgUrl+"&imgName="+row.annName; }else{ //如果沒有選中行,則提示用戶 showTip("請選擇一條記錄進行操作!"); }
});
說明:我使用的是easyui框架,數據是用datagrid中獲取的。
前台請求請使用同步請求,不要使用ajax方式,否則response輸出流會直接打印到瀏覽器后台中,而不會成為文件讓用戶下載。
2.Controller
@RequestMapping(params = "method=downloadImage") public void downloadImage(HttpServletRequest request, HttpServletResponse response) throws Exception{ //圖片的名稱 String imgName = request.getParameter("imgName"); //名稱轉碼,避免中文亂碼 imgName = new String(imgName.getBytes("iso8859-1"),"UTF-8"); //圖片的資源地址,http://10.80.3.229:8081/mediaserver/574fe515e30ab97c9068d2e1 //這是媒體服務器返回的地址,因為是網絡地址,所以需要使用HttpURLConnection去獲取圖片 String imgUrl = request.getParameter("imgUrl"); //輸入流,用來讀取圖片 InputStream ins = null; HttpURLConnection httpURL = null; //輸出流 OutputStream out = response.getOutputStream(); try{ URL url = new URL(imgUrl); //打開一個網絡連接 httpURL = (HttpURLConnection)url.openConnection(); //設置網絡連接超時時間 httpURL.setConnectTimeout(3000); //設置應用程序要從網絡連接讀取數據 httpURL.setDoInput(true); //設置請求方式 httpURL.setRequestMethod("GET"); //獲取請求返回碼 int responseCode = httpURL.getResponseCode(); if(responseCode == 200){ //如果響應為“200”,表示成功響應,則返回一個輸入流 ins = httpURL.getInputStream(); //設置response響應頭
//encodeChineseDownloadFileName()用來解決文件名為中文的問題,方法體在下面 response.setHeader("content-disposition", "attachment;filename="+ encodeChineseDownloadFileName(request,imgName)); //輸出流到response中 byte[] data = new byte[1024]; int len = 0; while((len = ins.read(data)) > 0){ out.write(data, 0, len); } } }catch(Exception e){ LogUtil.ERROR.error("下載附件圖片出錯!",e); }finally{ if(ins != null){ ins.close(); } if(out != null){ out.close(); } } } /* * 解決文件為中文名的亂碼問題 */ private String encodeChineseDownloadFileName(HttpServletRequest request, String pFileName) throws UnsupportedEncodingException{ String filename = null; //獲取請求頭中的瀏覽器標識 String agent = request.getHeader("USER-AGENT"); if(agent != null){ if(agent.indexOf("Firefox") != -1){ //Firefox filename = "=?UTF-8?B?" + (new String(Base64.encodeBase64(pFileName.getBytes("UTF-8")))) + "?="; }else if(agent.indexOf("Chrome") != -1){ //Chrome filename = new String(pFileName.getBytes(), "ISO8859-1"); }else{ //IE7+ filename = URLEncoder.encode(pFileName, "UTF-8"); //替換空格 filename = StringUtils.replace(filename, "+", "%20"); } }else{ filename = pFileName; } return filename; }