Download files, java download files
Binary Download
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 the file exists */if (File. exists () {String fileName = URLEncoder. encode (file. getName (), enc); response. reset (); Servlet Context servletContext = request. getServletContext (); response. setContentType (servletContext. getMimeType (fileName); response. addHeader ("Content-Disposition", "attachment; filename =" + fileName); int fileLength = (int) file. length (); response. setContentLength (fileLength);/* if the file length is greater than 0 */if (fileLength> 0) {/* Create input stream */InputStream inStream = null; ServletOutputStream outStream = null; try {limit E Am = new FileInputStream (file); byte [] buf = new byte [4096];/* Create output stream */outStream = response. getOutputStream (); int readLength; while (readLength = inStream. read (buf ))! =-1) {outStream. write (buf, 0, readLength) ;}} finally {inStream. close (); outStream. flush (); outStream. close ();}}}}
SpringMVC download
Public void downloadTemplate (HttpServletRequest request, HttpServletResponse response) 6 throws UnsupportedEncodingException {7 String path = request. getSession (). getServletContext (). getRealPath (""); 8 String filename = "template.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") handles safari garbled Problem 12 String fileName = new String (bytes, "ISO-8859-1"); 13 // sets the output format 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 (); // use the commons-io component to process file streams 21} catch (IOException e) {22 e. printStackTrace (); 23} finally {24 IOUtils. closeQuietly (inStream); 25}