Javaweb檔案上傳
阿新 • • 發佈:2021-09-05
匯入依賴
<!--檔案上傳--> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency>
前端頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <body> <%--檔案上傳--%> <form action="${pageContext.request.contextPath}/upload.do" method="post" enctype="multipart/form-data"> 上傳使用者: <input type="text" name="username"><br/> <p><input type="file" name="file1"></p> <p><input type="file" name="file1"></p> <input type="submit"> | <input type="reset"> </form> </body> </html>
後端程式碼
package com.xx.servlet; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.ProgressListener; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.UUID; /** * @author xx * @version 1.0 */ public class FileServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //判斷上傳的檔案是普通表單還是帶檔案的表單 if (!ServletFileUpload.isMultipartContent(req)) { return; //如果是普通的表單,終止方法執行,直接返回 } String msg = ""; try { //建立上傳檔案的儲存路輕。建議在WEB-INF路徑下,安全。使用者無法直接訪問上傳的檔案 String uploadPath = this.getServletContext().getRealPath("/WEB-INF/upload"); System.out.println("uploadPath=" + uploadPath); File uploadFile = new File(uploadPath); if (!uploadFile.exists()) { //建立目錄 uploadFile.mkdir(); } //快取,臨時檔案 //臨時路徑,加入檔案超過了預期的大小,我們就把它放到一個臨時檔案中,過幾天自動刪除,或者提醒使用者轉存為永久 String tmpPath = this.getServletContext().getRealPath("/WEB-INF/tmp"); File tmpFile = new File(tmpPath); if (!tmpFile.exists()) { tmpFile.mkdir(); //建立臨時目錄 } //處理上傳的文什,一般都需要通過流來獲取。我們可以使用request.getInputStream(),原生態的檔案上傳流獲取,十分麻煩 //建議使用Apache的檔案上傳元件來實現,commons-fileupload,它需要依賴於commons-io元件 //1.建立DiskFileItemFactory物件,處理檔案上傳路徑或者大小限制的 DiskFileItemFactory factory = new DiskFileItemFactory(); /*可不設定 //通過這個工廠設定一個緩衝區,當上傳的檔案大於這個緩衝區的時候,將它放到臨時檔案中 factory.setSizeThreshold(1024 * 1024); //緩衝區大小為1M factory.setRepository(tmpFile);*/ //2.獲取ServletFileUpload ServletFileUpload fileUpload = new ServletFileUpload(factory); /*可不設定 //監聽檔案上傳進度 fileUpload.setProgressListener(new ProgressListener() { @Override public void update(long l, long l1, int i) { System.out.println("總大小: " + l1 + " 已上傳: " + l); } }); //處理亂碼問題 fileUpload.setHeaderEncoding("UTF-8"); //設定單個檔案的最大值 fileUpload.setFileSizeMax(1024 * 1024 * 10); //設定總共能夠上傳檔案的大小 fileUpload.setSizeMax(1024 * 1024 * 10);*/ //3.處理上傳的檔案 //解析前端請求,封裝成一個FileItem物件 List<FileItem> fileItems = fileUpload.parseRequest(req); //fileItem 代表每一個表單物件 for (FileItem fileItem : fileItems) { //判斷上傳的檔案是普通的表單還是帶檔案的表單 if (fileItem.isFormField()) { //getFileName指的是前端表單控制元件的name String name = fileItem.getFieldName(); String value = fileItem.getString("UTF-8");//處理亂碼 System.out.println(name + ":" + value); } else { //檔案 //處理檔案 String fileItemName = fileItem.getName(); //可能存在檔名不合法的情況 if (fileItemName.trim().equals("") || fileItemName == null) { continue; } //獲取上傳的檔名 String fileName = fileItemName.substring(fileItemName.lastIndexOf("/") + 1); //獲取檔案的字尾名 String fileExtName = fileItemName.substring(fileItemName.lastIndexOf(".") + 1); //可以使用UUID(唯一識別的通用碼),保證檔名唯一 //UUID.randomUUID(),隨機生成一個唯一識別的通用碼 String uuidPath = UUID.randomUUID().toString(); //存放地址 //檔案真實存在的路徑 String realPath = uploadPath + "/" + uuidPath; //給每個檔案建立一個對應的資料夾 File realPathFile = new File(realPath); if (!realPathFile.exists()) { realPathFile.mkdir(); } //檔案傳輸 //獲取檔案上傳的流 InputStream inputStream = fileItem.getInputStream(); //建立一個檔案輸出流 //realPath = 真實的資料夾; //差了一個檔案; 加上輸出檔案的名字+"/ "+uuidFileName FileOutputStream fos = new FileOutputStream(realPath + "/" + fileName); //建立一個緩衝區 byte[] buffer = new byte[1024 * 1024]; //判斷是否讀取完畢 int len = 0; //如果大於0說明還存在資料 while ((len = inputStream.read(buffer)) > 0) { fos.write(buffer, 0, len); } //關閉流 fos.close(); inputStream.close(); msg = "檔案上傳成功"; fileItem.delete(); // 上傳成功,清除臨時檔案 } } } catch (FileUploadException e) { e.printStackTrace(); } req.setAttribute("msg", msg); req.getRequestDispatcher("/info.jsp").forward(req, resp); } }