1. 程式人生 > >JAVAWeb簡單檔案上傳

JAVAWeb簡單檔案上傳

版權宣告:本文為博主原創文章,未經博主允許不得轉載。https://blog.csdn.net/qq_40348465/article/details/83758904

1.先匯入兩個包:commons-fileupload-1.3.3.jar,commons-io-2.6.jar。

2.前端頁面程式碼

<form action="upLoadfile.do" method="post"
		enctype="multipart/form-data">
		<input type="text" name="username" /><br> 
		<input type="file" name="userimg" /><br> 
		<input type="submit" value="提交" />
</form>

2.Servlet程式碼

 

package com.uploadtest.upload;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class upLoadfile
 */
@WebServlet("/upLoadfile.do")
public class upLoadfile extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public upLoadfile() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String saveFileName = ""; //
		String oldFileName = ""; // 直接由item.getNam()獲取的檔名,有可能獲取的是路徑,也為了避免重名覆蓋,所以要對它進行處理
		String newFileName = ""; // 對原始檔名進行處理後的名字
		// 藉助工具解析commons-fileupload smartupload(在專案中匯入了jar包)
		// 判斷傳遞的是否是檔案型別,判斷form的enctype的屬性值是否是multipart/form-data
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart) {
			// 建立FileItem物件的工廠
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 獲取Servlet上下文
			ServletContext servletContext = null;
			servletContext = this.getServletConfig().getServletContext();
			// 獲取臨時資料夾
			String str = "javax.servlet.context.tempdir";
			File repository = (File) servletContext.getAttribute(str);
			factory.setRepository(repository);
			// 建立檔案上傳處理器
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 解決中文亂碼
			upload.setHeaderEncoding("utf-8");
			// 解析request獲取上傳的引數
			try {
				// 使用ServletFileUpload解析器解析上傳資料,解析結果返回的是一個List<FileItem>集合,每一個FileItem對應一個Form表單的輸入項
				List<FileItem> items = upload.parseRequest(request);
				// 解決上傳檔名的中文亂碼
				upload.setHeaderEncoding("UTF-8");
				// 處理引數
				for (FileItem item : items) {
					// 判斷是否為Form的表單域,即判斷是否為普通的資料,若不是則為檔案。
					if (item.isFormField()) {
						String name = item.getFieldName();
						// 解決普通輸入項的資料的中文亂碼問題
						String value = item.getString("UTF-8");
						// value = new String(value.getBytes("iso8859-1"),"UTF-8");
						//System.out.println(name + "=" + value);
					} else {
						// 設定上傳單個檔案的大小的最大值,目前是設定為1024*1024*10位元組,也就是10MB
						upload.setFileSizeMax(1024 * 1024 * 10);
						// 寫入檔案
						// 此處本專案在伺服器中的路徑,為絕對路徑,也可以根據需要存入到其他路徑
						String rootPath = servletContext.getRealPath("//");
						// File.separator(相當於添加了一個分隔符),在Windows下的路徑分隔符(\)和在Linux下的路徑分隔符(/)是不一樣的,當直接使用絕對路徑時,跨平臺會報異常						
						String savePath = rootPath + File.separator + "upload";
						/*  此處我是將檔案儲存在伺服器上的,這樣的話如果重寫部署一次伺服器,之前上傳的檔案就會刪除
						  如果想永久儲存上傳的檔案,可以設定一個其他絕對路徑,如:E:\eclipse-workspace\JAVAWeb\JSPUploadTest\WebContent\fileByupload。*/						 
						// String savePath = "E:\\eclipse-workspace\\JAVAWeb\\JSPUploadTest\\fileByupload";

						File fileSaveFolder = new File(savePath);
						// 如果不存在該資料夾則建立
						if (!fileSaveFolder.exists()) {
							fileSaveFolder.mkdir();
						}
						oldFileName = item.getName();
						newFileName = processFileName(oldFileName);
						saveFileName = savePath + File.separator + newFileName;
						// 儲存檔案
						File uploadedFile = new File(saveFileName);
						item.write(uploadedFile);
					}
				}
				request.setAttribute("message", "檔案上傳成功!");
			} catch (FileUploadBase.FileSizeLimitExceededException e) {
				e.printStackTrace();
				request.setAttribute("message", "照片大小不能超過10M");
				request.getRequestDispatcher("Show.jsp").forward(request, response);
				return;
			} catch (FileUploadException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			request.setAttribute("saveFileName", saveFileName);
			request.setAttribute("newFileName", newFileName);
			request.getRequestDispatcher("Show.jsp").forward(request, response);
		}
	}

	// 對檔名進行處理
	private String processFileName(String oldFileName) {
		// 補充:對於 item.getName()有的瀏覽器會返回檔名,而有的瀏覽器會返回“路徑”+“檔名”,針對後者我們需要通過“字串擷取”獲取檔名
		// 例如會出現這樣的情況:item.getName():C:\Users\Desktop\備忘錄.txt
		String tempFileName = "";
		int index = oldFileName.lastIndexOf("\\");
		if (index != -1) {
			// subString(x)是從字串的第x個字元擷取
			tempFileName = oldFileName.substring(index + 1);
		}
		// 為防止檔案覆蓋的現象發生,要為上傳檔案產生一個唯一的檔名
		return UUID.randomUUID().toString() + "_" + tempFileName;
	}
}

  3.圖片展示

  

 <p>${message}</p>
  <img id="picture" src="upload/${newFileName}" width="200px" height="200px" alt="不是圖片">