1. 程式人生 > 實用技巧 >E1. Weights Division (easy version) 解析(思維、優先佇列、樹狀DP)

E1. Weights Division (easy version) 解析(思維、優先佇列、樹狀DP)


<body>
	<form action="/UploadServlet" method="post" enctype="multipart/form-data">
		使用者名稱:<input name="uname"/>
				<br/>
		頭像:    <input type="file" name="upicture"/>
				<br/>
		      <input type="submit" value="提交"/>
	</form>
	
	<a href="DownloadServlet?filename=1.png">檔案下載</a>
</body>






@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet {

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		//獲取檔案上傳的路徑--伺服器路徑
		String realPath = request.getServletContext().getRealPath("/image/user");
		 File f = new File(realPath);
		 if(!f.exists()) {
			 f.mkdirs();
		 }
		
		//設定編碼
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=UTF-8");
		response.setCharacterEncoding("utf-8");
		
		try {
		 //判斷前臺的form是否是要上傳檔案
		boolean isMultipart = ServletFileUpload.isMultipartContent(request);
		if (isMultipart) {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			
			ServletFileUpload upload = new ServletFileUpload(factory);
			
			
			upload.setSizeMax(1024*200);//200kB
			
			//form中的所有請求欄位將儲存到 items集合中 包括使用者名稱和頭像,不能再用request.getParameter方法
			List<FileItem> items = upload.parseRequest(request);
			//遍歷集合,分別處理簡單資料和檔案資料
			Iterator<FileItem> iter = items.iterator();
			while (iter.hasNext()) {
				FileItem item = iter.next();
				//String itemName = item.getFieldName();
				if (item.isFormField()) {//普通欄位--使用者名稱
					String name = item.getString("UTF-8");
				}else {//檔案
					String fileName = item.getName();
					//判斷是否為圖片
					String ext = fileName.substring( fileName.indexOf(".")+1 ) ;
					if(!(ext.equals("png") || ext.equals("gif") ||ext.equals("jpg"))) {
						System.out.println("圖片型別有誤!格式只能是 png gif  jpg");
						return ;//終止
					}
					//處理圖片
					 String  newFileName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."), fileName.length());
					 
					 String path=realPath+File.separator+newFileName;
					 
					 File file = new File(path);
					 
					 item.write(file);// 上傳
					 System.out.println(fileName + "上傳成功!");
					 return;
				}
			}
		}
			
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}