1. 程式人生 > >關於servlet中檔案的上傳和下載

關於servlet中檔案的上傳和下載

關於servlet中檔案的上傳和下載
jar包
jar包

jsp頁面程式碼:

<script type="text/javascript">
	function addFile(){
		//得到div容器
		var div1 = document.getElementById("div1");
		div1.innerHTML +=  "<div><input type='file' name='photo' /><input type='button' value='刪除' onclick='delFile(this)'/><br /></div>";
	}
	
	function delFile(input){
		input.parentNode.parentNode.removeChild(input.parentNode);
	}
</script>
<body>
	<form enctype="multipart/form-data"
		action="${pageContext.request.contextPath }/servlet/uploadServlet2"
		method="post">
		<input type="text" name="name" /><br />
		<div id="div1">
			<div>
				<input type="file" name="photo" /><input type="button" value="新增" onclick="addFile()"/><br />
			</div>
			
		</div>
		<input type="submit" value="上傳" /><br />
	</form>
</body>

servlet程式碼

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
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.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

public class UploadServlet2 extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// request.setCharacterEncoding("UTF-8");
		// 要執行檔案上傳的操作
		// 判斷表單是否支援檔案上傳。即:enctype="multipart/form-data"
		boolean isMultipartContent = ServletFileUpload.isMultipartContent(request);
		if (!isMultipartContent) {
			throw new RuntimeException("your form is not multipart/form-data");
		}

		// 建立一個DiskFileItemfactory工廠類
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(new File("f:\\"));// 指定臨時檔案的儲存目錄
		// 建立一個ServletFileUpload核心物件
		ServletFileUpload sfu = new ServletFileUpload(factory);
		// 解決上傳表單項亂碼問題
		sfu.setHeaderEncoding("UTF-8");
		// 限制上傳檔案的大小

		// 解析request物件,並得到一個表單項的集合
		try {
			// sfu.setFileSizeMax(1024*1024*3);//表示3M大小
			// sfu.setSizeMax(1024*1024*6);
			List<FileItem> fileItems = sfu.parseRequest(request);

			// 遍歷表單項資料
			for (FileItem fileitem : fileItems) {
				if (fileitem.isFormField()) {
					// 普通表單項
					processFormField(fileitem);
				} else {
					// 上傳表單項
					processUploadField(fileitem);
				}
			}

		} catch (FileUploadBase.FileSizeLimitExceededException e) {
			// throw new RuntimeException("檔案過在,不能超過3M");

			System.out.println("檔案過在,不能超過3M");
		} catch (FileUploadBase.SizeLimitExceededException e) {
			System.out.println("總檔案大小不能超過6M");
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
	}

	private void processUploadField(FileItem fileitem) {
		try {
			// 得到檔案輸入流
			InputStream is = fileitem.getInputStream();

			// 建立一個檔案存檔的目錄
			String directoryRealPath = this.getServletContext().getRealPath(
					"/WEB-INF/upload");
			File storeDirectory = new File(directoryRealPath);// 即代表檔案又代表目錄
			if (!storeDirectory.exists()) {
				storeDirectory.mkdirs();// 建立一個指定的目錄
			}
			// 得到上傳的名子
			String filename = fileitem.getName();// 檔案項中的值 F:\圖片素材\小清新\43.jpg 或者
													// 43.jpg
			if (filename != null) {
				// filename =
				// filename.substring(filename.lastIndexOf(File.separator)+1);
				filename = FilenameUtils.getName(filename);// 效果同上
			}

			// 解決檔案同名的問題
			filename = UUID.randomUUID() + "_" + filename;
			// 目錄打散
			// String childDirectory = makeChildDirectory(storeDirectory); //
			// 2015-10-19
			String childDirectory = makeChildDirectory(storeDirectory, filename); // a/b

			// 上傳檔案,自動刪除臨時檔案
			fileitem.write(new File(storeDirectory, childDirectory
					+ File.separator + filename));
			fileitem.delete();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 上傳表單項
	private void processUploadField1(FileItem fileitem) {

		try {
			// 得到檔案輸入流
			InputStream is = fileitem.getInputStream();

			// 建立一個檔案存檔的目錄
			String directoryRealPath = this.getServletContext().getRealPath(
					"/WEB-INF/upload");
			File storeDirectory = new File(directoryRealPath);// 即代表檔案又代表目錄
			if (!storeDirectory.exists()) {
				storeDirectory.mkdirs();// 建立一個指定的目錄
			}
			// 得到上傳的名子
			String filename = fileitem.getName();// 檔案項中的值 F:\圖片素材\小清新\43.jpg 或者
													// 43.jpg
			// 處理檔名
			/*
			 * 解決此問題: F:\\apache-tomcat-7.0.52\\webapps\\day18_00_upload\\upload\\F:\\圖片素材\\小清新\\41.jpg
			 */
			if (filename != null) {
				// filename =
				// filename.substring(filename.lastIndexOf(File.separator)+1);
				filename = FilenameUtils.getName(filename);// 效果同上
			}

			// 解決檔案同名的問題
			filename = UUID.randomUUID() + "_" + filename;

			// 目錄打散
			// String childDirectory = makeChildDirectory(storeDirectory); //
			// 2015-10-19
			String childDirectory = makeChildDirectory(storeDirectory, filename); // 2015-10-19

			// 在storeDirectory下,建立完整目錄下的檔案
			File file = new File(storeDirectory, childDirectory
					+ File.separator + filename); // 絕對目錄/日期目錄/檔名
			// 通過檔案輸出流將上傳的檔案儲存到磁碟
			FileOutputStream fos = new FileOutputStream(file);

			int len = 0;
			byte[] b = new byte[1024];
			while ((len = is.read(b)) != -1) {
				fos.write(b, 0, len);
			}
			fos.close();
			is.close();

			fileitem.delete();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	// 目錄打散
	private String makeChildDirectory(File storeDirectory, String filename) {
		int hashcode = filename.hashCode();// 返回字元轉換的32位hashcode碼
		System.out.println(hashcode);
		String code = Integer.toHexString(hashcode); // 把hashcode轉換為16進位制的字元
														// abdsaf2131safsd
		System.out.println(code);
		String childDirectory = code.charAt(0) + File.separator
				+ code.charAt(1); // a/b
		// 建立指定目錄
		File file = new File(storeDirectory, childDirectory);
		if (!file.exists()) {
			file.mkdirs();
		}
		return childDirectory;
	}

	// 按日期打散
	/*
	 * private String makeChildDirectory(File storeDirectory) {
	 * 
	 * SimpleDateFormat sdf =new SimpleDateFormat("yyyy-MM-dd"); String
	 * dateDirectory = sdf.format(new Date()); //只管建立目錄 File file = new
	 * File(storeDirectory,dateDirectory); if(!file.exists()){ file.mkdirs(); }
	 * 
	 * return dateDirectory; }
	 */
	// 普通表單項
	private void processFormField(FileItem fileitem) {
		try {
			String fieldname = fileitem.getFieldName();// 欄位名
			String fieldvalue = fileitem.getString("UTF-8");// 欄位值
			//fieldvalue = new String(fieldvalue.getBytes("iso-8859-1"),"utf-8");
			System.out.println(fieldname + "=" + fieldvalue);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}