1. 程式人生 > >ajax非同步上傳圖片及其他表單項

ajax非同步上傳圖片及其他表單項

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-1.8.3.js"></script>
</head>
<script type="text/javascript">
	function upload() {
		var formData =new FormData($("#form")[0]);
		 $.ajax({
			 url:'${pageContext.request.contextPath }/UploadServlet',
			 data:formData,
			 type:'post',
			 processData:false,
			 contentType:false,
			 success:function(data){
				alert("成功了!")
			 }
		 }); 
		 
	  }
</script>
<body>
	<form id="form" id="form">
		檔名:<input id="name" name="name" type="text" /><br/>
		上傳檔案:<input type="file" name="file"/><br/>
		<input type="button" value="提交" onclick="upload()"/><br/>
	</form>
</body>
</html>
try {
			//接受上傳檔案
			
			//1、建立磁碟檔案項工廠
			DiskFileItemFactory factory = new DiskFileItemFactory();
			//2、建立檔案上傳的核心類
			ServletFileUpload upload = new ServletFileUpload(factory);
			
			//3、解析request---獲得檔案項集合
			List<FileItem> parseRequest = upload.parseRequest(request);

			//4、遍歷檔案項集合
			
			for(FileItem item : parseRequest){
				//5、判斷普通表單項/檔案上傳項
				boolean formField = item.isFormField();//是否是一個普通表單項
				if(formField){
					//普通表單項
					System.out.println(item.getFieldName() + ":" + item.getString());
				}
				else{
					//檔案上傳項
					//我們使用uuid生成檔名以防止亂碼
					String fileName = UUID.randomUUID().toString().replace("-","").trim();
					fileName = fileName + ".jpg";
					//獲得上傳檔案的內容
					InputStream in = item.getInputStream();
					//將in中的資料拷貝伺服器上
					String path = this.getServletContext().getRealPath("products");
					OutputStream out = new FileOutputStream(path+"/"+fileName);
					int len = 0;
					byte[] buffer = new byte[1024];
					while((len=in.read(buffer))>0){
						out.write(buffer, 0, len);
					}
					in.close();
					out.close();
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}