1. 程式人生 > 實用技巧 >【狂神說Java】JavaWeb-檔案上傳

【狂神說Java】JavaWeb-檔案上傳

記錄一下,以免以下幾個包導錯

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;

原始碼:

FileSerlvet類

package com.chen;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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;

/**
 * Servlet implementation class FileSerlvet
 */
public class FileSerlvet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		// response.getWriter().append("Served at: ").append(request.getContextPath());
		
		// 判斷上傳的檔案普通表單還是帶檔案的表單
		if (!ServletFileUpload.isMultipartContent(request)) {
			return;//終止方法執行,說明這是一個普通的表單,直接返回
		}
	    //建立上傳檔案的儲存路徑,建議在WEB-INF路徑下,安全,使用者無法直接訪間上傳的檔案;
	    String uploadPath =this.getServletContext().getRealPath("/WEB-INF/upload");
	    File uploadFile = new File(uploadPath);
	    if (!uploadFile.exists()){
	    uploadFile.mkdir(); //建立這個月錄
	    }
		
		// 建立上傳檔案的儲存路徑,建議在WEB-INF路徑下,安全,使用者無法直接訪問上傳的檔案
		String tmpPath = this.getServletContext().getRealPath("/WEB-INF/tmp");
		File file = new File(tmpPath);
		if (!file.exists()) {
			file.mkdir();//建立臨時目錄
		}

		// 處理上傳的檔案,一般都需要通過流來獲取,我們可以使用 request, getInputstream(),原生態的檔案上傳流獲取,十分麻煩
		// 但是我們都建議使用 Apache的檔案上傳元件來實現, common-fileupload,它需要旅 commons-io元件;
		try {
			// 建立DiskFileItemFactory物件,處理檔案路徑或者大小限制
			DiskFileItemFactory factory = getDiskFileItemFactory(file);
			/*
			 * //通過這個工廠設定一個緩衝區,當上傳的檔案大於這個緩衝區的時候,將他放到臨時檔案 factory.setSizeThreshold(1024 *
			 * 1024); //快取區大小為1M factory.setRepository (file);//臨時目錄的儲存目錄,需要一個File
			 */

			// 2、獲取ServletFileUpload
			ServletFileUpload upload = getServletFileUpload(factory);

			// 3、處理上傳檔案
			// 把前端請求解析,封裝成FileItem物件,需要從ServletFileUpload物件中獲取
			String msg = uploadParseRequest(upload, request, uploadPath);
			
			// Servlet請求轉發訊息
			System.out.println(msg);
			if(msg == "檔案上傳成功!") {
				// Servlet請求轉發訊息
				request.setAttribute("msg",msg);
				request.getRequestDispatcher("info.jsp").forward(request, response);
			}else {
				msg ="請上傳檔案";
				request.setAttribute("msg",msg);
				request.getRequestDispatcher("info.jsp").forward(request, response);
			}

		} catch (FileUploadException e) {
			// TODO 自動生成的 catch 塊
			e.printStackTrace();
		}
	}

	public static DiskFileItemFactory getDiskFileItemFactory(File file) {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 通過這個工廠設定一個緩衝區,當上傳的檔案大於這個緩衝區的時候,將他放到臨時檔案中;
		factory.setSizeThreshold(1024 * 1024);// 緩衝區大小為1M
		factory.setRepository(file);// 臨時目錄的儲存目錄,需要一個file
		return factory;
	}

	public static ServletFileUpload getServletFileUpload(DiskFileItemFactory factory) {
		ServletFileUpload upload = new ServletFileUpload(factory);
		// 監聽長傳進度
		upload.setProgressListener(new ProgressListener() {

			// pBYtesRead:已讀取到的檔案大小
			// pContextLength:檔案大小
			public void update(long pBytesRead, long pContentLength, int pItems) {
				System.out.println("總大小:" + pContentLength + "已上傳:" + pBytesRead);
			}
		});

		// 處理亂碼問題
		upload.setHeaderEncoding("UTF-8");
		// 設定單個檔案的最大值
		upload.setFileSizeMax(1024 * 1024 * 10);
		// 設定總共能夠上傳檔案的大小
		// 1024 = 1kb * 1024 = 1M * 10 = 10м

		return upload;
	}

	public static String uploadParseRequest(ServletFileUpload upload, HttpServletRequest request, String uploadPath)
			throws FileUploadException, IOException {

		String msg = "";
		
		// 把前端請求解析,封裝成FileItem物件
		List<FileItem> fileItems = upload.parseRequest(request);
		for (FileItem fileItem : fileItems) {
			if (fileItem.isFormField()) {// 判斷上傳的檔案是普通的表單還是帶檔案的表單
				// getFieldName指的是前端表單控制元件的name;
				String name = fileItem.getFieldName();
				String value = fileItem.getString("UTF-8"); // 處理亂碼
				System.out.println(name + ": " + value);
			} else {// 判斷它是上傳的檔案
				
				// ============處理檔案==============

				// 拿到檔名
				String uploadFileName = fileItem.getName();
				System.out.println("上傳的檔名: " + uploadFileName);
				if (uploadFileName.trim().equals("") || uploadFileName == null) {
					continue;
				}

				// 獲得上傳的檔名/images/girl/paojie.png
				String fileName = uploadFileName.substring(uploadFileName.lastIndexOf("/") + 1);
				// 獲得檔案的字尾名
				String fileExtName = uploadFileName.substring(uploadFileName.lastIndexOf(".") + 1);

				/*
				 * 如果檔案字尾名fileExtName不是我們所需要的 就直按return.不處理,告訴使用者檔案型別不對。
				 */

				System.out.println("檔案資訊[件名: " + fileName + " ---檔案型別" + fileExtName + "]");
				// 可以使用UID(唯一識別的通用碼),保證檔名唯
				// 0UID. randomUUID(),隨機生一個唯一識別的通用碼;
				String uuidPath = UUID.randomUUID().toString();
				
				// ================處理檔案完畢==============

				// 存到哪? uploadPath
				// 檔案真實存在的路徑realPath
				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(); // 上傳成功,清除臨時檔案
				//=============檔案傳輸完成=============
			}
		}
		return msg;

	}
}

註冊xml

<servlet>
  	<servlet-name>upload</servlet-name>
  	<servlet-class>com.chen.FileSerlvet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>upload</servlet-name>
  	<url-pattern>/upload.do</url-pattern>

匯入依賴的jar包

	<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.4</version>
		</dependency>
	<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.6</version>
		</dependency>

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
	<body>
		<%--
		GET:上傳檔案大小有限制
		POST:上傳檔案大小沒有限制
		 ${pageContext.request.contextPath}
		 --%>
		<form action="upload.do" enctype="multipart/form-data"  method="post">
			上傳使用者:<input type="text" name="username"><br/>
			<P><input type="file" name="file1"></P>
			<P><input type="file" name="file1"></P>
			<P><input type="submit" value="提交"> | <input type="reset"></P>
		</form>
	</body>
</html>

info.jsp

<%@ page language="java" contentType="text/html;charset=UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>Insert title here</title>
</head>
<body>

<%=request.getAttribute("msg")%>

</body>
</html>