圖片上傳和批量上傳

圖片上傳和批量上傳

一: 導入jar包
commons-fileupload-1.3.jar
commons-io-2.4.jar
二: 前端jsp頁面代碼
1.form表單屬性

method="post"
enctype="multipart/form-data"

2.上傳input
name是取上傳的文件的關鍵

<input type="file" name="file" id="file" accept=""/>

3.單圖片上傳
servlet代碼

		String realFileName=UUID.randomUUID().toString(); //生成UUID,避免上傳文件名重複
		Part part =request.getPart("file"); //雙引號內需是前端file的name
		String newFilename =realFileName+".jpg"; //上傳的圖片重命名
		//獲取項目的根目錄
		String filePath = request.getSession().getServletContext().getRealPath("/");
		//需要提前在項目下建一個文件夾upload
		filePath = filePath+"upload"; 
		this.getServletContext().log("上傳路徑爲:" +filePath); 
		String path=filePath + "\\" + newFilename; //最後圖片的上傳位置和圖片名
		part.write(path);//執行上傳
		System.out.println(path);

4.批量上傳
servlet代碼

			String header="";//輔助字符串
			List<Part> parts = (List<Part>) request.getParts();//partlist
			for(Part part : parts) {//遍歷
				 if (part.getName().startsWith("file"))// 前端是input的file類型判斷
					 {
					 header = part.getHeader("Content-Disposition");
					 if(!header.substring(header.length()-2,header.length()).equals("\"\"")){// 有文件上傳了,前端代碼和我寫一樣纔行
						 String realFileName=UUID.randomUUID().toString(); 
							String newFilename =realFileName+".jpg"; 
							String filePath = request.getSession().getServletContext().getRealPath("/");
							filePath = filePath+"upload"; 
							this.getServletContext().log("上傳路徑爲:" +filePath); 
							String path=filePath + "\\" + newFilename; 
							part.write(path);
							System.out.println(path);
					 }
				}
			}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章