java檔案上傳和下載
- 簡介
檔案上傳和下載是java web中常見的操作,檔案上傳主要是將檔案通過IO流傳放到伺服器的某一個特定的資料夾下,而檔案下載則是與檔案上傳相反,將檔案從伺服器的特定的資料夾下的檔案通過IO流下載到本地。
對於檔案上傳,瀏覽器在上傳的過程中是將檔案以流的形式提交到伺服器端的,如果直接使用Servlet獲取上傳檔案的輸入流然後再解析裡面的請求引數是比較麻煩,所以一般選擇採用apache的開源工具common-fileupload這個檔案上傳元件。這個common-fileupload上傳元件的jar包可以去apache官網上面下載,也可以在struts的lib資料夾下面找到,struts上傳的功能就是基於這個實現的。common-fileupload是依賴於common-io這個包的,所以還需要下載這個包。
- 檔案上傳
1、檔案上傳頁面和訊息提示頁面
upload.jsp頁面的程式碼如下:
<%@ page language="java" pageEncoding="UTF-8"%> <!DOCTYPE HTML> <html> <head> <title>檔案上傳</title> </head> <body> <form action="${pageContext.request.contextPath}/servlet/uploadHandleServlet2"enctype="multipart/form-data" method="post" 上傳使用者:<input type="text" name="username"><br/> 上傳檔案1:<input type="file" name="file1"><br/> 上傳檔案2:<input type="file" name="file2"><br/> <input type="submit" value="提交"> </form></body> </html>
在檔案上傳的頁面要用enctype="multipart/form-data" method="post"來表示進行檔案上傳。
2、處理檔案上傳的Servlet
public class UploadHandleServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //得到上傳檔案的儲存目錄,將上傳的檔案存放於WEB-INF目錄下,不允許外界直接訪問,保證上傳檔案的安全 String savePath = this.getServletContext().getRealPath("/WEB-INF/upload"); File file = new File(savePath); if(!file.exists()&&!file.isDirectory()){ System.out.println("目錄或檔案不存在!"); file.mkdir(); } //訊息提示 String message = ""; try { //使用Apache檔案上傳元件處理檔案上傳步驟: //1、建立一個DiskFileItemFactory工廠 DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); //2、建立一個檔案上傳解析器 ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory); //解決上傳檔名的中文亂碼 fileUpload.setHeaderEncoding("UTF-8"); //3、判斷提交上來的資料是否是上傳表單的資料 if(!fileUpload.isMultipartContent(request)){ //按照傳統方式獲取資料 return; } //4、使用ServletFileUpload解析器解析上傳資料,解析結果返回的是一個List<FileItem>集合,每一個FileItem對應一個Form表單的輸入項 List<FileItem> list = fileUpload.parseRequest(request); for (FileItem item : list) { //如果fileitem中封裝的是普通輸入項的資料 if(item.isFormField()){ String name = item.getFieldName(); //解決普通輸入項的資料的中文亂碼問題 String value = item.getString("UTF-8"); String value1 = new String(name.getBytes("iso8859-1"),"UTF-8"); System.out.println(name+" "+value); System.out.println(name+" "+value1); }else{ //如果fileitem中封裝的是上傳檔案,得到上傳的檔名稱, String fileName = item.getName(); System.out.println(fileName); if(fileName==null||fileName.trim().equals("")){ continue; } //注意:不同的瀏覽器提交的檔名是不一樣的,有些瀏覽器提交上來的檔名是帶有路徑的,如: c:\a\b\1.txt,而有些只是單純的檔名,如:1.txt //處理獲取到的上傳檔案的檔名的路徑部分,只保留檔名部分 fileName = fileName.substring(fileName.lastIndexOf(File.separator)+1); //獲取item中的上傳檔案的輸入流 InputStream is = item.getInputStream(); //建立一個檔案輸出流 FileOutputStream fos = new FileOutputStream(savePath+File.separator+fileName); //建立一個緩衝區 byte buffer[] = new byte[1024]; //判斷輸入流中的資料是否已經讀完的標識 int length = 0; //迴圈將輸入流讀入到緩衝區當中,(len=in.read(buffer))>0就表示in裡面還有資料 while((length = is.read(buffer))>0){ //使用FileOutputStream輸出流將緩衝區的資料寫入到指定的目錄(savePath + "\\" + filename)當中 fos.write(buffer, 0, length); } //關閉輸入流 is.close(); //關閉輸出流 fos.close(); //刪除處理檔案上傳時生成的臨時檔案 item.delete(); message = "檔案上傳成功"; } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); message = "檔案上傳失敗"; } request.setAttribute("message",message); request.getRequestDispatcher("/message.jsp").forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
3、檔案上傳的細節
上述的程式碼雖然可以成功將檔案上傳到伺服器上面的指定目錄當中,但是檔案上傳功能有許多需要注意的小細節問題,以下列出的幾點需要特別注意的:
(1)、為保證伺服器安全,上傳檔案應該放在外界無法直接訪問的目錄下,比如放於WEB-INF目錄下。
(2)、為防止檔案覆蓋的現象發生,要為上傳檔案產生一個唯一的檔名。
(3)、為防止一個目錄下面出現太多檔案,要使用hash演算法打散儲存。
(4)、要限制上傳檔案的最大值。
(5)、要限制上傳檔案的型別,在收到上傳檔名時,判斷後綴名是否合法。
4、改進後的servlet
public class UploadHandleServlet1 extends HttpServlet{ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //得到上傳檔案的儲存目錄,將上傳的檔案存放於WEB-INF目錄下,不允許外界直接訪問,保證上傳檔案的安全 String savePath = this.getServletContext().getRealPath("/WEB-INF/upload"); //上傳時生成的臨時檔案儲存目錄 String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp"); File file = new File(tempPath); if(!file.exists()&&!file.isDirectory()){ System.out.println("目錄或檔案不存在!"); file.mkdir(); } //訊息提示 String message = ""; try { //使用Apache檔案上傳元件處理檔案上傳步驟: //1、建立一個DiskFileItemFactory工廠 DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); //設定工廠的緩衝區的大小,當上傳的檔案大小超過緩衝區的大小時,就會生成一個臨時檔案存放到指定的臨時目錄當中。 diskFileItemFactory.setSizeThreshold(1024*100); //設定上傳時生成的臨時檔案的儲存目錄 diskFileItemFactory.setRepository(file); //2、建立一個檔案上傳解析器 ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory); //解決上傳檔名的中文亂碼 fileUpload.setHeaderEncoding("UTF-8"); //監聽檔案上傳進度 fileUpload.setProgressListener(new ProgressListener(){ public void update(long pBytesRead, long pContentLength, int arg2) { System.out.println("檔案大小為:" + pContentLength + ",當前已處理:" + pBytesRead); } }); //3、判斷提交上來的資料是否是上傳表單的資料 if(!fileUpload.isMultipartContent(request)){ //按照傳統方式獲取資料 return; } //設定上傳單個檔案的大小的最大值,目前是設定為1024*1024位元組,也就是1MB fileUpload.setFileSizeMax(1024*1024); //設定上傳檔案總量的最大值,最大值=同時上傳的多個檔案的大小的最大值的和,目前設定為10MB fileUpload.setSizeMax(1024*1024*10); //4、使用ServletFileUpload解析器解析上傳資料,解析結果返回的是一個List<FileItem>集合,每一個FileItem對應一個Form表單的輸入項 List<FileItem> list = fileUpload.parseRequest(request); for (FileItem item : list) { //如果fileitem中封裝的是普通輸入項的資料 if(item.isFormField()){ String name = item.getFieldName(); //解決普通輸入項的資料的中文亂碼問題 String value = item.getString("UTF-8"); String value1 = new String(name.getBytes("iso8859-1"),"UTF-8"); System.out.println(name+" "+value); System.out.println(name+" "+value1); }else{ //如果fileitem中封裝的是上傳檔案,得到上傳的檔名稱, String fileName = item.getName(); System.out.println(fileName); if(fileName==null||fileName.trim().equals("")){ continue; } //注意:不同的瀏覽器提交的檔名是不一樣的,有些瀏覽器提交上來的檔名是帶有路徑的,如: c:\a\b\1.txt,而有些只是單純的檔名,如:1.txt //處理獲取到的上傳檔案的檔名的路徑部分,只保留檔名部分 fileName = fileName.substring(fileName.lastIndexOf(File.separator)+1); //得到上傳檔案的副檔名 String fileExtName = fileName.substring(fileName.lastIndexOf(".")+1); if("zip".equals(fileExtName)||"rar".equals(fileExtName)||"tar".equals(fileExtName)||"jar".equals(fileExtName)){ request.setAttribute("message", "上傳檔案的型別不符合!!!"); request.getRequestDispatcher("/message.jsp").forward(request, response); return; } //如果需要限制上傳的檔案型別,那麼可以通過檔案的副檔名來判斷上傳的檔案型別是否合法 System.out.println("上傳檔案的副檔名為:"+fileExtName); //獲取item中的上傳檔案的輸入流 InputStream is = item.getInputStream(); //得到檔案儲存的名稱 fileName = mkFileName(fileName); //得到檔案儲存的路徑 String savePathStr = mkFilePath(savePath, fileName); System.out.println("儲存路徑為:"+savePathStr); //建立一個檔案輸出流 FileOutputStream fos = new FileOutputStream(savePathStr+File.separator+fileName); //建立一個緩衝區 byte buffer[] = new byte[1024]; //判斷輸入流中的資料是否已經讀完的標識 int length = 0; //迴圈將輸入流讀入到緩衝區當中,(len=in.read(buffer))>0就表示in裡面還有資料 while((length = is.read(buffer))>0){ //使用FileOutputStream輸出流將緩衝區的資料寫入到指定的目錄(savePath + "\\" + filename)當中 fos.write(buffer, 0, length); } //關閉輸入流 is.close(); //關閉輸出流 fos.close(); //刪除處理檔案上傳時生成的臨時檔案 item.delete(); message = "檔案上傳成功"; } } } catch (FileUploadBase.FileSizeLimitExceededException e) { e.printStackTrace(); request.setAttribute("message", "單個檔案超出最大值!!!"); request.getRequestDispatcher("/message.jsp").forward(request, response); return; }catch (FileUploadBase.SizeLimitExceededException e) { e.printStackTrace(); request.setAttribute("message", "上傳檔案的總的大小超出限制的最大值!!!"); request.getRequestDispatcher("/message.jsp").forward(request, response); return; }catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); message = "檔案上傳失敗"; } request.setAttribute("message",message); request.getRequestDispatcher("/message.jsp").forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } //生成上傳檔案的檔名,檔名以:uuid+"_"+檔案的原始名稱 public String mkFileName(String fileName){ return UUID.randomUUID().toString()+"_"+fileName; } public String mkFilePath(String savePath,String fileName){ //得到檔名的hashCode的值,得到的就是filename這個字串物件在記憶體中的地址 int hashcode = fileName.hashCode(); int dir1 = hashcode&0xf; int dir2 = (hashcode&0xf0)>>4; //構造新的儲存目錄 String dir = savePath + "\\" + dir1 + "\\" + dir2; //File既可以代表檔案也可以代表目錄 File file = new File(dir); if(!file.exists()){ file.mkdirs(); } return dir; } }
5、如果在檔案上傳中IO流成為了系統的效能瓶頸,可以考慮使用NIO來提高效能。改進servlet程式碼如下:
public class UploadHandleServlet2 extends HttpServlet{ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //得到上傳檔案的儲存目錄,將上傳的檔案存放於WEB-INF目錄下,不允許外界直接訪問,保證上傳檔案的安全 String savePath = this.getServletContext().getRealPath("/WEB-INF/upload"); //上傳時生成的臨時檔案儲存目錄 String tempPath = this.getServletContext().getRealPath("/WEB-INF/temp"); File file = new File(tempPath); if(!file.exists()&&!file.isDirectory()){ System.out.println("目錄或檔案不存在!"); file.mkdir(); } //訊息提示 String message = ""; try { //使用Apache檔案上傳元件處理檔案上傳步驟: //1、建立一個DiskFileItemFactory工廠 DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory(); //設定工廠的緩衝區的大小,當上傳的檔案大小超過緩衝區的大小時,就會生成一個臨時檔案存放到指定的臨時目錄當中。 diskFileItemFactory.setSizeThreshold(1024*100); //設定上傳時生成的臨時檔案的儲存目錄 diskFileItemFactory.setRepository(file); //2、建立一個檔案上傳解析器 ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory); //解決上傳檔名的中文亂碼 fileUpload.setHeaderEncoding("UTF-8"); //監聽檔案上傳進度 fileUpload.setProgressListener(new ProgressListener(){ public void update(long pBytesRead, long pContentLength, int arg2) { System.out.println("檔案大小為:" + pContentLength + ",當前已處理:" + pBytesRead); } }); //3、判斷提交上來的資料是否是上傳表單的資料 if(!fileUpload.isMultipartContent(request)){ //按照傳統方式獲取資料 return; } //設定上傳單個檔案的大小的最大值,目前是設定為1024*1024位元組,也就是1MB fileUpload.setFileSizeMax(1024*1024); //設定上傳檔案總量的最大值,最大值=同時上傳的多個檔案的大小的最大值的和,目前設定為10MB fileUpload.setSizeMax(1024*1024*10); //4、使用ServletFileUpload解析器解析上傳資料,解析結果返回的是一個List<FileItem>集合,每一個FileItem對應一個Form表單的輸入項 List<FileItem> list = fileUpload.parseRequest(request); for (FileItem item : list) { //如果fileitem中封裝的是普通輸入項的資料 if(item.isFormField()){ String name = item.getFieldName(); //解決普通輸入項的資料的中文亂碼問題 String value = item.getString("UTF-8"); String value1 = new String(name.getBytes("iso8859-1"),"UTF-8"); System.out.println(name+" "+value); System.out.println(name+" "+value1); }else{ //如果fileitem中封裝的是上傳檔案,得到上傳的檔名稱, String fileName = item.getName(); System.out.println(fileName); if(fileName==null||fileName.trim().equals("")){ continue; } //注意:不同的瀏覽器提交的檔名是不一樣的,有些瀏覽器提交上來的檔名是帶有路徑的,如: c:\a\b\1.txt,而有些只是單純的檔名,如:1.txt //處理獲取到的上傳檔案的檔名的路徑部分,只保留檔名部分 fileName = fileName.substring(fileName.lastIndexOf(File.separator)+1); //得到上傳檔案的副檔名 String fileExtName = fileName.substring(fileName.lastIndexOf(".")+1); if("zip".equals(fileExtName)||"rar".equals(fileExtName)||"tar".equals(fileExtName)||"jar".equals(fileExtName)){ request.setAttribute("message", "上傳檔案的型別不符合!!!"); request.getRequestDispatcher("/message.jsp").forward(request, response); return; } //如果需要限制上傳的檔案型別,那麼可以通過檔案的副檔名來判斷上傳的檔案型別是否合法 System.out.println("上傳檔案的副檔名為:"+fileExtName); //獲取item中的上傳檔案的輸入流 InputStream fis = item.getInputStream(); //得到檔案儲存的名稱 fileName = mkFileName(fileName); //得到檔案儲存的路徑 String savePathStr = mkFilePath(savePath, fileName); System.out.println("儲存路徑為:"+savePathStr); //建立一個檔案輸出流 FileOutputStream fos = new FileOutputStream(savePathStr+File.separator+fileName); //獲取讀通道 FileChannel readChannel = ((FileInputStream)fis).getChannel(); //獲取讀通道 FileChannel writeChannel = fos.getChannel(); //建立一個緩衝區 ByteBuffer buffer = ByteBuffer.allocate(1024); //判斷輸入流中的資料是否已經讀完的標識 int length = 0; //迴圈將輸入流讀入到緩衝區當中,(len=in.read(buffer))>0就表示in裡面還有資料 while(true){ buffer.clear(); int len = readChannel.read(buffer);//讀入資料 if(len < 0){ break;//讀取完畢 } buffer.flip(); writeChannel.write(buffer);//寫入資料 } //關閉輸入流 fis.close(); //關閉輸出流 fos.close(); //刪除處理檔案上傳時生成的臨時檔案 item.delete(); message = "檔案上傳成功"; } } } catch (FileUploadBase.FileSizeLimitExceededException e) { e.printStackTrace(); request.setAttribute("message", "單個檔案超出最大值!!!"); request.getRequestDispatcher("/message.jsp").forward(request, response); return; }catch (FileUploadBase.SizeLimitExceededException e) { e.printStackTrace(); request.setAttribute("message", "上傳檔案的總的大小超出限制的最大值!!!"); request.getRequestDispatcher("/message.jsp").forward(request, response); return; }catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); message = "檔案上傳失敗"; } request.setAttribute("message",message); request.getRequestDispatcher("/message.jsp").forward(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } //生成上傳檔案的檔名,檔名以:uuid+"_"+檔案的原始名稱 public String mkFileName(String fileName){ return UUID.randomUUID().toString()+"_"+fileName; } public String mkFilePath(String savePath,String fileName){ //得到檔名的hashCode的值,得到的就是filename這個字串物件在記憶體中的地址 int hashcode = fileName.hashCode(); int dir1 = hashcode&0xf; int dir2 = (hashcode&0xf0)>>4; //構造新的儲存目錄 String dir = savePath + "\\" + dir1 + "\\" + dir2; //File既可以代表檔案也可以代表目錄 File file = new File(dir); if(!file.exists()){ file.mkdirs(); } return dir; } }
- 檔案下載
1、列出提供下載的檔案資源
要將Web應用系統中的檔案資源提供給使用者進行下載,首先我們要有一個頁面列出上傳檔案目錄下的所有檔案,當用戶點選檔案下載超連結時就進行下載操作,編寫一個ListFileServlet,用於列出Web應用系統中所有下載檔案。
ListFileServlet程式碼如下
public class ListFileServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub //獲取上傳檔案的目錄 String uploadFilePath = this.getServletContext().getRealPath("/WEB-INF/upload"); //儲存要下載的檔名 Map<String, String> fileMap = new HashMap<String, String>(); //遞迴遍歷filepath目錄下的所有檔案和目錄,將檔案的檔名儲存到map集合中 fileList(new File(uploadFilePath),fileMap); //將Map集合傳送到listfile.jsp頁面進行顯示 request.setAttribute("fileMap", fileMap); request.getRequestDispatcher("/listfile.jsp").forward(request, response); } //遞迴遍歷指定目錄下的所有檔案 public void fileList(File file,Map fileMap){ //如果file代表的不是一個檔案,而是一個目錄 if(!file.isFile()){ //列出該目錄下的所有檔案和目錄 File[] files = file.listFiles(); //遍歷files[]陣列 for (File file2 : files) { System.out.println(file2.getName()); //遞迴 fileList(file2, fileMap); } }else{ /* 處理檔名,上傳後的檔案是以uuid_檔名的形式去重新命名的,去除檔名的uuid_部分 file.getName().indexOf("_")檢索字串中第一次出現"_"字元的位置,如果檔名類似於:9349249849-88343-8344_阿_凡_達.avi 那麼file.getName().substring(file.getName().indexOf("_")+1)處理之後就可以得到阿_凡_達.avi部分 */ String realName = file.getName().substring(file.getName().lastIndexOf("_")+1); //file.getName()得到的是檔案的原始名稱,這個名稱是唯一的,因此可以作為key,realName是處理過後的名稱,有可能會重複 fileMap.put(file.getName(), realName); } } }
說明一下,一般檔案路徑在資料庫中儲存,然後再資料庫中查詢結果在頁面顯示。
listfile.jsp頁面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE HTML> <html> <head> <title>下載檔案顯示頁面</title> </head> <body> <!-- 遍歷Map集合 --> <c:forEach var="me" items="${fileMap}"> <c:url value="/servlet/downLoadServlet" var="downurl"> <c:param name="filename" value="${me.key}"></c:param> </c:url> ${me.value}<a href="${downurl}">下載</a> <br/> </c:forEach> </body> </html>
2、檔案下載
DownLoadServlet的程式碼如下:
public class DownLoadServlet extends HttpServlet{ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //得到要下載的檔名 String fileName = request.getParameter("filename"); fileName = new String(fileName.getBytes("iso8859-1"),"UTF-8"); //上傳的檔案都是儲存在/WEB-INF/upload目錄下的子目錄當中 String fileSaveRootPath=this.getServletContext().getRealPath("/WEB-INF/upload"); // 處理檔名 String realname = fileName.substring(fileName.indexOf("_")+1); //通過檔名找出檔案的所在目錄 String path = findFileSavePathByFileName(fileName,fileSaveRootPath); //得到要下載的檔案 File file = new File(path+File.separator+fileName); //如果檔案不存在 if(!file.exists()){ request.setAttribute("message", "您要下載的資源已被刪除!!"); request.getRequestDispatcher("/message.jsp").forward(request, response); return; } //設定響應頭,控制瀏覽器下載該檔案 response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8")); //讀取要下載的檔案,儲存到檔案輸入流 FileInputStream fis = new FileInputStream(path + File.separator + fileName); //建立輸出流 OutputStream fos = response.getOutputStream(); //設定快取區 ByteBuffer buffer = ByteBuffer.allocate(1024); //輸入通道 FileChannel readChannel = fis.getChannel(); //輸出通道 FileChannel writeChannel = ((FileOutputStream)fos).getChannel(); while(true){ buffer.clear(); int len = readChannel.read(buffer);//讀入資料 if(len < 0){ break;//傳輸結束 } buffer.flip(); writeChannel.write(buffer);//寫入資料 } //關閉輸入流 fis.close(); //關閉輸出流 fos.close(); } @Ove