二進制下載
public void download(HttpServletRequest request, HttpServletResponse response) throws IOException{ //String filePath = "src/main/webapp/apk/android/NCB.apk"; String filePath=request.getSession().getServletContext().getRealPath("/apk/android/NCB.apk"); File file = new File(filePath); /* 如果文件存在 */ if (file.exists()) { String fileName = URLEncoder.encode(file.getName(), enc); response.reset(); ServletContext servletContext=request.getServletContext(); response.setContentType(servletContext.getMimeType(fileName)); response.addHeader("Content-Disposition", "attachment; filename=" + fileName); int fileLength = (int) file.length(); response.setContentLength(fileLength); /* 如果文件長度大於0 */ if (fileLength > 0) { /* 創建輸入流 */ InputStream inStream = null; ServletOutputStream outStream = null; try { inStream = new FileInputStream(file); byte[] buf = new byte[4096]; /* 創建輸出流 */ outStream = response.getOutputStream(); int readLength; while (((readLength = inStream.read(buf)) != -1)) { outStream.write(buf, 0, readLength); } } finally { inStream.close(); outStream.flush(); outStream.close(); } } } }
springMVC下載
public void downloadTemplate(HttpServletRequest request, HttpServletResponse response) 6 throws UnsupportedEncodingException { 7 String path = request.getSession().getServletContext().getRealPath(""); 8 String filename = "模板文件.xls"; 9 File file = new File(path + "\\file\\templagte\\" + filename); 10 String userAgent = request.getHeader("User-Agent"); 11 byte[] bytes = userAgent.contains("MSIE") ? filename.getBytes() : filename.getBytes("UTF-8"); // fileName.getBytes("UTF-8")處理safari的亂碼問題 12 String fileName = new String(bytes, "ISO-8859-1"); 13 // 設置輸出的格式 14 response.setContentType("multipart/form-data"); 15 response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8")); 16 17 InputStream inStream = null; 18 try { 19 inStream = new FileInputStream(file); 20 IOUtils.copy(inStream, response.getOutputStream());//使用commons-io組件進行文件流的處理 21 } catch (IOException e) { 22 e.printStackTrace(); 23 }finally{ 24 IOUtils.closeQuietly(inStream); 25 }