java中下載檔案寫法之一
阿新 • • 發佈:2019-01-30
沒什麼想說的。。。。。。。。
@RequestMapping(value="download",method = RequestMethod.GET) public void downloadFileAction(HttpServletRequest request,HttpServletResponse response) throws IOException { response.setCharacterEncoding(request.getCharacterEncoding());//設定編碼 System.out.println(request.getCharacterEncoding()); response.setContentType("application/octet-stream;charset=utf-8");//內容為二進位制流。 FileInputStream fis = null;//輸入流 try { File file = new File("C:\\Users\\YangWenHui\\Desktop\\雜物\\表名.txt"); fis = new FileInputStream(file);//寫入下載檔案的路徑 // response.addHeader("Content-Type", ""); response.setHeader("Content-Disposition", "attachment; filename="+new String(file.getName().getBytes("UTF-8"),"ISO-8859-1"));//設定下載檔案中有中文名稱的 System.out.println(file.getName()); // IOUtils.copy(fis,response.getOutputStream()); // response.flushBuffer(); BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream()); BufferedInputStream bis = new BufferedInputStream(fis); int length = 0; byte[] temp = new byte[1 * 1024 * 10];//一次讀取多大 while((length = bis.read(temp)) != -1) {//讀取檔案 bos.write(temp, 0, length); } bos.flush(); bis.close(); bos.close(); }catch(FileNotFoundException e){ e.printStackTrace(); }catch(IOException e) { e.printStackTrace(); }finally { fis.close(); } }