SSM網頁下載檔案
阿新 • • 發佈:2019-01-14
效果:
需要的資源:
commons-fileupload-1.3.1.jar,commons-io-1.3.2.jar
步驟:
1:搭建SSM框架:
2:在配置檔案springconfig.xml中新增配置
<!-- 定義檔案上傳解析器 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 設定預設編碼 --> <property name="defaultEncoding" value="UTF-8" /> <!-- 設定檔案上傳的最大值5MB,5*1024*1024 --> <property name="maxUploadSize" value="5242880" /> <property name="maxInMemorySize" value="4096" /> </bean>
3:編寫下載jsp檔案:download.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>下載檔案</title> </head> <body> <h1>檔案下載例項</h1> <form action="${pageContext.request.contextPath}/download.action" method="get"> <input type="submit" value="下載"> </form> </body> </html>
4:編輯控制器:
/** * 檔案下載功能 * @param request * @param response * @throws Exception */ @RequestMapping("/download") @ResponseBody public String down(HttpServletRequest request,HttpServletResponse response) throws Exception{ //模擬檔案,myfile.txt為需要下載的檔案 String fileName = request.getSession().getServletContext().getRealPath("upload")+"/myfile.txt"; //獲取輸入流 InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName))); //假如以中文名下載的話 String filename = "下載檔案.txt"; //轉碼,免得檔名中文亂碼 filename = URLEncoder.encode(filename,"UTF-8"); //設定檔案下載頭 response.addHeader("Content-Disposition", "attachment;filename=" + filename); //1.設定檔案ContentType型別,這樣設定,會自動判斷下載檔案型別 response.setContentType("multipart/form-data"); BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream()); int len = 0; while((len = bis.read()) != -1){ out.write(len); out.flush(); } out.close(); return "login2"; }
5:執行,成功的話頁面資訊如下,點選下載看是否能正常下載: