java檔案上傳和下載
-
簡介
檔案上傳和下載是java web中常見的操作,檔案上傳主要是將檔案通過IO流傳放到伺服器的某一個特定的資料夾下,而檔案下載則是與檔案上傳相反,將檔案從伺服器的特定的資料夾下的檔案通過IO流下載到本地。
對於檔案上傳,瀏覽器在上傳的過程中是將檔案以流的形式提交到伺服器端的,如果直接使用Servlet獲取上傳檔案的輸入流然後再解析裡面的請求引數是比較麻煩,所以一般選擇採用apache的開源工具common-fileupload這個檔案上傳元件。這個common-fileupload上傳元件的jar包可以去apache官網上面下載,也可以在struts的lib資料夾下面找到,struts上傳的功能就是基於這個實現的。common-fileupload是依賴於common-io這個包的,所以還需要下載這個包。
-
檔案上傳
1、檔案上傳頁面和訊息提示頁面
upload.jsp頁面的程式碼如下:
1 <%@ page language="java" pageEncoding="UTF-8"%> 2 <!DOCTYPE HTML> 3 <html> 4 <head> 5 <title>檔案上傳</title> 6 </head> 7 8 <body> 9 <form action="${pageContext.request.contextPath}/servlet/uploadHandleServlet2" enctype="multipart/form-data" method="post" 上傳使用者:<input type="text" name="username"><br/> 10 上傳檔案1:<input type="file" name="file1"><br/> 11 上傳檔案2:<input type="file" name="file2"><br/> 12 <input type="submit" value="提交"> 13 </form> 14 </body> 15 </html>
在檔案上傳的頁面要用enctype="multipart/form-data" method="post"來表示進行檔案上傳。
2、處理檔案上傳的Servlet
1 public class UploadHandleServlet extends HttpServlet{ 2 3 @Override 4 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 5 //得到上傳檔案的儲存目錄,將上傳的檔案存放於WEB-INF目錄下,不允許外界直接訪問,保證上傳檔案的安全 6 String savePath = this.getServletContext().getRealPath("/WEB-INF/upload"); 7 File file = new File(savePath); 8 if(!file.exists()&&!file.isDirectory()){ 9 System.out.println("目錄或檔案不存在!"); 10 file.mkdir(); 11 } 12 //訊息提示 13 String message = ""; 14 try { 15 //使用Apache檔案上傳元件處理檔案上傳步驟: 16 //1、建立一個DiskFileItemFactory工廠 17 DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); 18 //2、建立一個檔案上傳解析器 19 ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory); 20 //解決上傳檔名的中文亂碼 21 fileUpload.setHeaderEncoding("UTF-8"); 22 //3、判斷提交上來的資料是否是上傳表單的資料 23 if(!fileUpload.isMultipartContent(request)){ 24 //按照傳統方式獲取資料 25 return; 26 } 27 //4、使用ServletFileUpload解析器解析上傳資料,解析結果返回的是一個List<FileItem>集合,每一個FileItem對應一個Form表單的輸入項 28 List<FileItem> list = fileUpload.parseRequest(request); 29 for (FileItem item : list) { 30 //如果fileitem中封裝的是普通輸入項的資料 31 if(item.isFormField()){ 32 String name = item.getFieldName(); 33 //解決普通輸入項的資料的中文亂碼問題 34 String value = item.getString("UTF-8"); 35 String value1 = new String(name.getBytes("iso8859-1"),"UTF-8"); 36 System.out.println(name+" "+value); 37 System.out.println(name+" "+value1); 38 }else{ 39 //如果fileitem中封裝的是上傳檔案,得到上傳的檔名稱, 40 String fileName = item.getName(); 41 System.out.println(fileName); 42 if(fileName==null||fileName.trim().equals("")){ 43 continue; 44 } 45 //注意:不同的瀏覽器提交的檔名是不一樣的,有些瀏覽器提交上來的檔名是帶有路徑的,如: c:\a\b\1.txt,而有些只是單純的檔名,如:1.txt 46 //處理獲取到的上傳檔案的檔名的路徑部分,只保留檔名部分 47 fileName = fileName.substring(fileName.lastIndexOf(File.separator)+1); 48 //獲取item中的上傳檔案的輸入流 49 InputStream is = item.getInputStream(); 50 //建立一個檔案輸出流 51 FileOutputStream fos = new FileOutputStream(savePath+File.separator+fileName); 52 //建立一個緩衝區 53 byte buffer[] = new byte[1024]; 54 //判斷輸入流中的資料是否已經讀完的標識 55 int length = 0; 56 //迴圈將輸入流讀入到緩衝區當中,(len=in.read(buffer))>0就表示in裡面還有資料 57 while((length = is.read(buffer))>0){ 58 //使用FileOutputStream輸出流將緩衝區的資料寫入到指定的目錄(savePath + "\\" + filename)當中 59 fos.write(buffer, 0, length); 60 } 61 //關閉輸入流 62 is.close(); 63 //關閉輸出流 64 fos.close(); 65 //刪除處理檔案上傳時生成的臨時檔案 66 item.delete(); 67 message = "檔案上傳成功"; 68 } 69 } 70 } catch (FileUploadException e) { 71 // TODO Auto-generated catch block 72 e.printStackTrace(); 73 message = "檔案上傳失敗"; 74 } 75 request.setAttribute("message",message); 76 request.getRequestDispatcher("/message.jsp").forward(request, response); 77 } 78 79 @Override 80 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 81 doGet(request, response); 82 } 83 84 }
3、檔案上傳的細節
上述的程式碼雖然可以成功將檔案上傳到伺服器上面的指定目錄當中,但是檔案上傳功能有許多需要注意的小細節問題,以下列出的幾點需要特別注意的:
(1)、為保證伺服器安全,上傳檔案應該放在外界無法直接訪問的目錄下,比如放於WEB-INF目錄下。
(2)、為防止檔案覆蓋的現象發生,要為上傳檔案產生一個唯一的檔名。
(3)、為防止一個目錄下面出現太多檔案,要使用hash演算法打散儲存。
(4)、要限制上傳檔案的最大值。
(5)、要限制上傳檔案的型別,在收到上傳檔名時,判斷後綴名是否合法。
4、改進後的servlet
1 public class UploadHandleServlet1 extends HttpServlet{ 2 3 @Override 4 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 5 //得到上傳檔案的儲存目錄,將上傳的檔案存放於WEB-INF目錄下,不允許外界直接訪問,保證上傳檔案的安全 6 String savePath = this.getServletContext().getRealPath("/WEB-INF/upload"); 7 //上傳時生成的臨時檔案儲存目錄 8 String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp"); 9 File file = new File(tempPath); 10 if(!file.exists()&&!file.isDirectory()){ 11 System.out.println("目錄或檔案不存在!"); 12 file.mkdir(); 13 } 14 //訊息提示 15 String message = ""; 16 try { 17 //使用Apache檔案上傳元件處理檔案上傳步驟: 18 //1、建立一個DiskFileItemFactory工廠 19 DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); 20 //設定工廠的緩衝區的大小,當上傳的檔案大小超過緩衝區的大小時,就會生成一個臨時檔案存放到指定的臨時目錄當中。 21 diskFileItemFactory.setSizeThreshold(1024*100); 22 //設定上傳時生成的臨時檔案的儲存目錄 23 diskFileItemFactory.setRepository(file); 24 //2、建立一個檔案上傳解析器 25 ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory); 26 //解決上傳檔名的中文亂碼 27 fileUpload.setHeaderEncoding("UTF-8"); 28 //監聽檔案上傳進度 29 fileUpload.setProgressListener(new ProgressListener(){ 30 public void update(long pBytesRead, long pContentLength, int arg2) { 31 System.out.println("檔案大小為:" + pContentLength + ",當前已處理:" + pBytesRead); 32 } 33 }); 34 //3、判斷提交上來的資料是否是上傳表單的資料 35 if(!fileUpload.isMultipartContent(request)){ 36 //按照傳統方式獲取資料 37 return; 38 } 39 //設定上傳單個檔案的大小的最大值,目前是設定為1024*1024位元組,也就是1MB 40 fileUpload.setFileSizeMax(1024*1024); 41 //設定上傳檔案總量的最大值,最大值=同時上傳的多個檔案的大小的最大值的和,目前設定為10MB 42 fileUpload.setSizeMax(1024*1024*10); 43 //4、使用ServletFileUpload解析器解析上傳資料,解析結果返回的是一個List<FileItem>集合,每一個FileItem對應一個Form表單的輸入項 44 List<FileItem> list = fileUpload.parseRequest(request); 45 for (FileItem item : list) { 46 //如果fileitem中封裝的是普通輸入項的資料 47 if(item.isFormField()){ 48 String name = item.getFieldName(); 49 //解決普通輸入項的資料的中文亂碼問題 50 String value = item.getString("UTF-8"); 51 String value1 = new String(name.getBytes("iso8859-1"),"UTF-8"); 52 System.out.println(name+" "+value); 53 System.out.println(name+" "+value1); 54 }else{ 55 //如果fileitem中封裝的是上傳檔案,得到上傳的檔名稱, 56 String fileName = item.getName(); 57 System.out.println(fileName); 58 if(fileName==null||fileName.trim().equals("")){ 59 continue; 60 } 61 //注意:不同的瀏覽器提交的檔名是不一樣的,有些瀏覽器提交上來的檔名是帶有路徑的,如: c:\a\b\1.txt,而有些只是單純的檔名,如:1.txt 62 //處理獲取到的上傳檔案的檔名的路徑部分,只保留檔名部分 63 fileName = fileName.substring(fileName.lastIndexOf(File.separator)+1); 64 //得到上傳檔案的副檔名 65 String fileExtName = fileName.substring(fileName.lastIndexOf(".")+1); 66 if("zip".equals(fileExtName)||"rar".equals(fileExtName)||"tar".equals(fileExtName)||"jar".equals(fileExtName)){ 67 request.setAttribute("message", "上傳檔案的型別不符合!!!"); 68 request.getRequestDispatcher("/message.jsp").forward(request, response); 69 return; 70 } 71 //如果需要限制上傳的檔案型別,那麼可以通過檔案的副檔名來判斷上傳的檔案型別是否合法 72 System.out.println("上傳檔案的副檔名為:"+fileExtName); 73 //獲取item中的上傳檔案的輸入流 74 InputStream is = item.getInputStream(); 75 //得到檔案儲存的名稱 76 fileName = mkFileName(fileName); 77 //得到檔案儲存的路徑 78 String savePathStr = mkFilePath(savePath, fileName); 79 System.out.println("儲存路徑為:"+savePathStr); 80 //建立一個檔案輸出流 81 FileOutputStream fos = new FileOutputStream(savePathStr+File.separator+fileName); 82 //建立一個緩衝區 83 byte buffer[] = new byte[1024]; 84 //判斷輸入流中的資料是否已經讀完的標識 85 int length = 0; 86 //迴圈將輸入流讀入到緩衝區當中,(len=in.read(buffer))>0就表示in裡面還有資料 87 while((length = is.read(buffer))>0){ 88 //使用FileOutputStream輸出流將緩衝區的資料寫入到指定的目錄(savePath + "\\" + filename)當中 89 fos.write(buffer, 0, length); 90 } 91 //關閉輸入流 92 is.close(); 93 //關閉輸出流 94 fos.close(); 95 //刪除處理檔案上傳時生成的臨時檔案 96 item.delete(); 97 message = "檔案上傳成功"; 98 } 99 } 100 } catch (FileUploadBase.FileSizeLimitExceededException e) { 101 e.printStackTrace(); 102 request.setAttribute("message", "單個檔案超出最大值!!!"); 103 request.getRequestDispatcher("/message.jsp").forward(request, response); 104 return; 105 }catch (FileUploadBase.SizeLimitExceededException e) { 106 e.printStackTrace(); 107 request.setAttribute("message", "上傳檔案的總的大小超出限制的最大值!!!"); 108 request.getRequestDispatcher("/message.jsp").forward(request, response); 109 return; 110 }catch (FileUploadException e) { 111 // TODO Auto-generated catch block 112 e.printStackTrace(); 113 message = "檔案上傳失敗"; 114 } 115 request.setAttribute("message",message); 116 request.getRequestDispatcher("/message.jsp").forward(request, response); 117 } 118 119 @Override 120 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 121 doGet(request, response); 122 } 123 //生成上傳檔案的檔名,檔名以:uuid+"_"+檔案的原始名稱 124 public String mkFileName(String fileName){ 125 return UUID.randomUUID().toString()+"_"+fileName; 126 } 127 public String mkFilePath(String savePath,String fileName){ 128 //得到檔名的hashCode的值,得到的就是filename這個字串物件在記憶體中的地址 129 int hashcode = fileName.hashCode(); 130 int dir1 = hashcode&0xf; 131 int dir2 = (hashcode&0xf0)>>4; 132 //構造新的儲存目錄 133 String dir = savePath + "\\" + dir1 + "\\" + dir2; 134 //File既可以代表檔案也可以代表目錄 135 File file = new File(dir); 136 if(!file.exists()){ 137 file.mkdirs(); 138 } 139 return dir; 140 } 141 }
5、如果在檔案上傳中IO流成為了系統的效能瓶頸,可以考慮使用NIO來提高效能。改進servlet程式碼如下:
1 public class UploadHandleServlet2 extends HttpServlet{ 2 3 @Override 4 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 5 //得到上傳檔案的儲存目錄,將上傳的檔案存放於WEB-INF目錄下,不允許外界直接訪問,保證上傳檔案的安全 6 String savePath = this.getServletContext().getRealPath("/WEB-INF/upload"); 7 //上傳時生成的臨時檔案儲存目錄 8 String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp"); 9 File file = new File(tempPath); 10 if(!file.exists()&&!file.isDirectory()){ 11 System.out.println("目錄或檔案不存在!"); 12 file.mkdir(); 13 } 14 //訊息提示 15 String message = ""; 16 try { 17 //使用Apache檔案上傳元件處理檔案上傳步驟: 18 //1、建立一個DiskFileItemFactory工廠 19 DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); 20 //設定工廠的緩衝區的大小,當上傳的檔案大小超過緩衝區的大小時,就會生成一個臨時檔案存放到指定的臨時目錄當中。 21 diskFileItemFactory.setSizeThreshold(1024*100); 22 //設定上傳時生成的臨時檔案的儲存目錄 23 diskFileItemFactory.setRepository(file); 24 //2、建立一個檔案上傳解析器 25 ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory); 26 //解決上傳檔名的中文亂碼 27 fileUpload.setHeaderEncoding("UTF-8"); 28 //監聽檔案上傳進度 29 fileUpload.setProgressListener(new ProgressListener(){ 30 public void update(long pBytesRead, long pContentLength, int arg2) { 31 System.out.println("檔案大小為:" + pContentLength + ",當前已處理:" + pBytesRead); 32 } 33 }); 34 //3、判斷提交上來的資料是否是上傳表單的資料 35 if(!fileUpload.isMultipartContent(request)){ 36 //按照傳統方式獲取資料 37 return; 38 } 39 //設定上傳單個檔案的大小的最大值,目前是設定為1024*1024位元組,也就是1MB 40 fileUpload.setFileSizeMax(1024*1024); 41 //設定上傳檔案總量的最大值,最大值=同時上傳的多個檔案的大小的最大值的和,目前設定為10MB 42 fileUpload.setSizeMax(1024*1024*10); 43 //4、使用ServletFileUpload解析器解析上傳資料,解析結果返回的是一個List<FileItem>集合,每一個FileItem對應一個Form表單的輸入項 44 List<FileItem> list = fileUpload.parseRequest(request); 45 for (FileItem item : list) { 46 //如果fileitem中封裝的是普通輸入項的資料 47 if(item.isFormField()){ 48 String name = item.getFieldName(); 49 //解決普通輸入項的資料的中文亂碼問題 50 String value = item.getString("UTF-8"); 51 String value1 = new String(name.getBytes("iso8859-1"),"UTF-8"); 52 System.out.println(name+" "+value); 53 System.out.println(name+" "+value1); 54 }else{ 55 //如果fileitem中封裝的是上傳檔案,得到上傳的檔名稱, 56 String fileName = item.getName(); 57 System.out.println(fileName); 58 if(fileName==null||fileName.trim().equals("")){ 59 continue; 60 } 61 //注意:不同的瀏覽器提交的檔名是不一樣的,有些瀏覽器提交上來的檔名是帶有路徑的,如: c:\a\b\1.txt,而有些只是單純的檔名,如:1.txt 62 //處理獲取到的上傳檔案的檔名的路徑部分,只保留檔名部分 63 fileName = fileName.substring(fileName.lastIndexOf(File.separator)+1); 64 //得到上傳檔案的副檔名 65 String fileExtName = fileName.substring(fileName.lastIndexOf(".")+1); 66 if("zip".equals(fileExtName)||"rar".equals(fileExtName)||"tar".equals(fileExtName)||"jar".equals(fileExtName)){ 67 request.setAttribute("message", "上傳檔案的型別不符合!!!"); 68 request.getRequestDispatcher("/message.jsp").forward(request, response); 69 return; 70 } 71 //如果需要限制上傳的檔案型別,那麼可以通過檔案的副檔名來判斷上傳的檔案型別是否合法 72 System.out.println("上傳檔案的副檔名為:"+fileExtName); 73 //獲取item中的上傳檔案的輸入流 74 InputStream fis = item.getInputStream(); 75 //得到檔案儲存的名稱 76 fileName = mkFileName(fileName); 77 //得到檔案儲存的路徑 78 String savePathStr = mkFilePath(savePath, fileName); 79 System.out.println("儲存路徑為:"+savePathStr); 80 //建立一個檔案輸出流 81 FileOutputStream fos = new FileOutputStream(savePathStr+File.separator+fileName); 82 //獲取讀通道 83 FileChannel readChannel = ((FileInputStream)fis).getChannel(); 84 //獲取讀通道 85 FileChannel writeChannel = fos.getChannel(); 86 //建立一個緩衝區 87 ByteBuffer buffer = ByteBuffer.allocate(1024); 88 //判斷輸入流中的資料是否已經讀完的標識 89 int length = 0; 90 //迴圈將輸入流讀入到緩衝區當中,(len=in.read(buffer))>0就表示in裡面還有資料 91 while(true){ 92 buffer.clear(); 93 int len = readChannel.read(buffer);//讀入資料 94 if(len < 0){ 95 break;//讀取完畢 96 } 97 buffer.flip(); 98 writeChannel.write(buffer);//寫入資料 99 } 100 //關閉輸入流 101 fis.close(); 102 //關閉輸出流 103 fos.close(); 104 //刪除處理檔案上傳時生成的臨時檔案 105 item.delete(); 106 message = "檔案上傳成功"; 107 } 108 } 109 } catch (FileUploadBase.FileSizeLimitExceededException e) { 110 e.printStackTrace(); 111 request.setAttribute("message", "單個檔案超出最大值!!!"); 112 request.getRequestDispatcher("/message.jsp").forward(request, response); 113 return; 114 }catch (FileUploadBase.SizeLimitExceededException e) { 115 e.printStackTrace(); 116 request.setAttribute("message", "上傳檔案的總的大小超出限制的最大值!!!"); 117 request.getRequestDispatcher("/message.jsp").forward(request, response); 118 return; 119 }catch (FileUploadException e) { 120 // TODO Auto-generated catch block 121 e.printStackTrace(); 122 message = "檔案上傳失敗"; 123 } 124 request.setAttribute("message",message); 125 request.getRequestDispatcher("/message.jsp").forward(request, response); 126 } 127 128 @Override 129 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 130 doGet(request, response); 131 } 132 //生成上傳檔案的檔名,檔名以:uuid+"_"+檔案的原始名稱 133 public String mkFileName(String fileName){ 134 return UUID.randomUUID().toString()+"_"+fileName; 135 } 136 public String mkFilePath(String savePath,String fileName){ 137 //得到檔名的hashCode的值,得到的就是filename這個字串物件在記憶體中的地址 138 int hashcode = fileName.hashCode(); 139 int dir1 = hashcode&0xf; 140 int dir2 = (hashcode&0xf0)>>4; 141 //構造新的儲存目錄 142 String dir = savePath + "\\" + dir1 + "\\" + dir2; 143 //File既可以代表檔案也可以代表目錄 144 File file = new File(dir); 145 if(!file.exists()){ 146 file.mkdirs(); 147 } 148 return dir; 149 } 150 }
-
檔案下載
1、列出提供下載的檔案資源
要將Web應用系統中的檔案資源提供給使用者進行下載,首先我們要有一個頁面列出上傳檔案目錄下的所有檔案,當用戶點選檔案下載超連結時就進行下載操作,編寫一個ListFileServlet,用於列出Web應用系統中所有下載檔案。
ListFileServlet程式碼如下:
1 public class ListFileServlet extends HttpServlet{ 2 @Override 3 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 4 doPost(request, response); 5 } 6 @Override 7 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 8 // TODO Auto-generated method stub 9 //獲取上傳檔案的目錄 10 String uploadFilePath = this.getServletContext().getRealPath("/WEB-INF/upload"); 11 //儲存要下載的檔名 12 Map<String, String> fileMap = new HashMap<String, String>(); 13 //遞迴遍歷filepath目錄下的所有檔案和目錄,將檔案的檔名儲存到map集合中 14 fileList(new File(uploadFilePath),fileMap); 15 //將Map集合傳送到listfile.jsp頁面進行顯示 16 request.setAttribute("fileMap", fileMap); 17 request.getRequestDispatcher("/listfile.jsp").forward(request, response); 18 19 } 20 //遞迴遍歷指定目錄下的所有檔案 21 public void fileList(File file,Map fileMap){ 22 //如果file代表的不是一個檔案,而是一個目錄 23 if(!file.isFile()){ 24 //列出該目錄下的所有檔案和目錄 25 File[] files = file.listFiles(); 26 //遍歷files[]陣列 27 for (File file2 : files) { 28 System.out.println(file2.getName()); 29 //遞迴 30 fileList(file2, fileMap); 31 } 32 }else{ 33 /* 處理檔名,上傳後的檔案是以uuid_檔名的形式去重新命名的,去除檔名的uuid_部分 34 file.getName().indexOf("_")檢索字串中第一次出現"_"字元的位置,如果檔名類似於:9349249849-88343-8344_阿_凡_達.avi 35 那麼file.getName().substring(file.getName().indexOf("_")+1)處理之後就可以得到阿_凡_達.avi部分 36 */ 37 String realName = file.getName().substring(file.getName().lastIndexOf("_")+1); 38 //file.getName()得到的是檔案的原始名稱,這個名稱是唯一的,因此可以作為key,realName是處理過後的名稱,有可能會重複 39 fileMap.put(file.getName(), realName); 40 } 41 } 42 }
說明一下,一般檔案路徑在資料庫中儲存,然後再資料庫中查詢結果在頁面顯示。
listfile.jsp頁面
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 3 <!DOCTYPE HTML> 4 <html> 5 <head> 6 <title>下載檔案顯示頁面</title> 7 </head> 8 9 <body> 10 <!-- 遍歷Map集合 --> 11 <c:forEach var="me" items="${fileMap}"> 12 <c:url value="/servlet/downLoadServlet" var="downurl"> 13 <c:param name="filename" value="${me.key}"></c:param> 14 </c:url> 15 ${me.value}<a href="${downurl}">下載</a> 16 <br/> 17 </c:forEach> 18 </body> 19 </html>
2、檔案下載
DownLoadServlet的程式碼如下:
1 public class DownLoadServlet extends HttpServlet{ 2 3 @Override 4 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 5 //得到要下載的檔名 6 String fileName = request.getParameter("filename"); 7 fileName = new String(fileName.getBytes("iso8859-1"),"UTF-8"); 8 //上傳的檔案都是儲存在/WEB-INF/upload目錄下的子目錄當中 9 String fileSaveRootPath=this.getServletContext().getRealPath("/WEB-INF/upload"); 10 // 處理檔名 11 String realname = fileName.substring(fileName.indexOf("_")+1); 12 //通過檔名找出檔案的所在目錄 13 String path = findFileSavePathByFileName(fileName,fileSaveRootPath); 14 //得到要下載的檔案 15 File file = new File(path+File.separator+fileName); 16 //如果檔案不存在 17 if(!file.exists()){ 18 request.setAttribute("message", "您要下載的資源已被刪除!!"); 19 request.getRequestDispatcher("/message.jsp").forward(request, response); 20 return; 21 } 22 23 //設定響應頭,控制瀏覽器下載該檔案 24 response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8")); 25 //讀取要下載的檔案,儲存到檔案輸入流 26 FileInputStream fis = new FileInputStream(path + File.separator + fileName); 27 //建立輸出流 28 OutputStream fos = response.getOutputStream(); 29 //設定快取區 30 ByteBuffer buffer = ByteBuffer.allocate(1024); 31 //輸入通道 32 FileChannel readChannel = fis.getChannel(); 33 //輸出通道 34 FileChannel writeChannel = ((FileOutputStream)fos).getChannel(); 35 while(true){ 36 buffer.clear(); 37 int len = readChannel.read(buffer);//讀入資料 38 if(len < 0){ 39 break;//傳輸結束 40 } 41 buffer.flip(); 42 writeChannel.write(buffer);//寫入資料 43 } 44 //關閉輸入流 45 fis.close(); 46 //關閉輸出流 47 fos.close(); 48 } 49 50 @Override 51 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 52 doPost(request, response); 53 } 54 //通過檔名和儲存上傳檔案根目錄找出要下載的檔案的所在路徑 55 public String findFileSavePathByFileName(String fileName,String fileSaveRootPath){ 56 int hashcode = fileName.hashCode(); 57 int dir1 = hashcode&0xf; 58 int dir2 = (hashcode&0xf0)>>4; 59 String dir = fileSaveRootPath + "\\" + dir1 + "\\" + dir2; 60 File file = new File(dir); 61 if(!file.exists()){ 62 file.mkdirs(); 63 } 64 return dir; 65 } 66 }
3、如果IO成為系統的瓶頸,可以考慮使用NIO來實現下載,提供系統性能
改進後的DownloadServlet程式碼如下:
1 public class DownLoadServlet1 extends HttpServlet{ 2 3 @Override 4 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 5 //得到要下載的檔名 6 String fileName = request.getParameter("filename"); 7 fileName = new String(fileName.getBytes("iso8859-1"),"UTF-8"); 8 //上傳的檔案都是儲存在/WEB-INF/upload目錄下的子目錄當中 9 String fileSaveRootPath=this.getServletContext().getRealPath("/WEB-INF/upload"); 10 // 處理檔名 11 String realname = fileName.substring(fileName.indexOf("_")+1); 12 //通過檔名找出檔案的所在目錄 13 String path = findFileSavePathByFileName(fileName,fileSaveRootPath); 14 //得到要下載的檔案 15 File file = new File(path+File.separator+fileName); 16 //如果檔案不存在 17 if(!file.exists()){ 18 request.setAttribute("message", "您要下載的資源已被刪除!!"); 19 request.getRequestDispatcher("/message.jsp").forward(request, response); 20 return; 21 } 22 23 //設定響應頭,控制瀏覽器下載該檔案 24 response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8")); 25 //讀取要下載的檔案,儲存到檔案輸入流 26 FileInputStream in = new FileInputStream(path + File.separator + fileName); 27 //建立輸出流 28 OutputStream os = response.getOutputStream(); 29 //設定快取區 30 byte[] bytes = new byte[1024]; 31 int len = 0; 32 while((len = in.read(bytes))>0){ 33 os.write(bytes); 34 } 35 //關閉輸入流 36 in.close(); 37 //關閉輸出流 38 os.close(); 39 } 40 41 @Override 42 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 43 doPost(request, response); 44 } 45 //通過檔名和儲存上傳檔案根目錄找出要下載的檔案的所在路徑 46 public String findFileSavePathByFileName(String fileName,String fileSaveRootPath){ 47 int hashcode = fileName.hashCode(); 48 int dir1 = hashcode&0xf; 49 int dir2 = (hashcode&0xf0)>>4; 50 String dir = fileSaveRootPath + "\\" + dir1 + "\\" + dir2; 51 File file = new File(dir); 52 if(!file.exists()){ 53 file.mkdirs(); 54 } 55 return dir; 56 } 57 }
以上內容參考部落格:http://www.cnblogs.com/xdp-gacl/p/4200090.html
FAQ:
fileupload外掛呼叫upload.parseRequest(request)解析得到空值問題
我是在SpringBoot下測試時,發現的該問題,即在解析請求時List list = upload.parseRequest(request);得到的list size=0,也就是根本沒有得到檔案資料。我在網上搜索該問題的解決方法,大致有以下兩種:
(1)原因在於Spring的配置檔案中已經配置了MultipartResolver,導致檔案上傳請求已經被預處理過了,所以此處解析檔案列表為空,對應的做法是刪除該段配置。
(2)認為是structs的過濾器導致請求已被預處理,所以也要修改對應過濾器的配置。
然而,在SpringBoot下,上述兩種解決方法不可能做到,因為SpringBoot的相關配置都是自己完成的,根本沒有顯示的配置檔案。況且以上兩種解決方法,修改配置檔案可能影響整個工程的其他部分,所以得另尋方案。
我通過斷點除錯該Controller程式碼,發現傳入的引數HttpServletRequest例項已經為StandardMultipartHttpServletRequest 物件了,且其結構中包含整個form表單的所有欄位資訊,我就想,區別於網上已有的兩種解決方案,總是想避免這種預處理,何不就利用這種預處理,來簡化自己的程式碼結構呢?於是就有了下面的解決程式碼。其方法很簡單,就是對傳入的request做強制轉型,從而可以根據StandardMultipartHttpServletRequest 例項方法得到相關form表單資料,從而大大簡化程式碼結構,示意如下:
@RequestMapping(value = "/file")
@ResponseBody
public String file (HttpServletRequest request, HttpServletResponse response) throws IOException {
...
try {
StandardMultipartHttpServletRequest req = (StandardMultipartHttpServletRequest) request;
Iterator<String> iterator = req.getFileNames();
while (iterator.hasNext()) {
MultipartFile file = req.getFile(iterator.next());
String fileNames = file.getOriginalFilename();
int split = fileNames.lastIndexOf(".");
//儲存檔案
//檔名 fileNames.substring(0,split)
//檔案格式 fileNames.substring(split+1,fileNames.length())
//檔案內容 file.getBytes()
...
}
}catch (Exception e){
e.printStackTrace();
return "fail";
}
return "success";
}