圖二
這個用到了response對象的contenttype,保存不同的文件需要不同的contenttype(具體可上網(wǎng)查)。
點擊備份執(zhí)行backUpSmu()函數(shù)具體實現(xiàn)如下:
function backUpSmu(){ Ext.Msg.wait('提示','正在備份,請稍后...'); Ext.Ajax.request({ success:function(res){ //alert(res.responseText);
//通過執(zhí)行window.open()來打開一個下載框圖二 window.open('group.do?method=download&&fileName='+res.responseText); Ext.Msg.hide(); } }); }
java后臺執(zhí)行流操作。進入action group的download()方法。
public ActionForward download(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { try { request.setCharacterEncoding("iso-8859-1"); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String fileName = request.getParameter( "fileName" ); BufferedInputStream bis = null; BufferedOutputStream bos = null; OutputStream os = null; InputStream is = null; String filePath = servlet.getServletContext().getRealPath("/" + ROOT + fileName);//項目路徑 try { File downloadFile = new File(filePath); is = new FileInputStream(downloadFile); bis = new BufferedInputStream(is); os = response.getOutputStream(); bos = new BufferedOutputStream(os); fileName = java.net.URLEncoder.encode(fileName, "UTF-8");//處理中文文件名的問題 fileName = new String(fileName.getBytes("UTF-8"),"GBK");//處理中文文件名的問題 response.reset(); response.setCharacterEncoding("utf-8"); response.setContentType("application/octet-stream");//文件類型contenttype response.setHeader("Content-Disposition","attachment; filename=" + fileName); //關(guān)鍵部分,打開一個下載框 int bytesRead = 0; byte[] buffer = new byte[8192]; while((bytesRead = bis.read(buffer,0,8192)) != -1) { bos.write(buffer, 0, bytesRead); } bos.flush(); is.close(); bis.close(); os.close(); bos.close(); } catch(Exception e){ e.printStackTrace(); } System.gc(); return null; }
至此可最終實現(xiàn)在extjs中的文件下載功能。
|