AngularJS實現文件異步上傳

第一篇博客直接開門見山了。。。。。。。。。

實現:前端AngularJs+後端servelthtml

依賴包:commons-fileupload.x.x.jar commons-io-x.x.jar前端

下載: http://commons.apache.org/proper/commons-fileupload/
http://commons.apache.org/proper/commons-io/ 文件上傳前端利用AngularJs封好的http發起異步請求傳遞二進制文件。 代碼: 第一步:java

<div class="row " ng-show="up_doc">
			<div class="col-md-12 col-sm-12">
				<div class="z_up_common">
					<div class="z_up_common_inner">
						<div class="z_up_image">
							<input id="file"
								onchange="angular.element(this).scope().file_up_onclick(this)"
								type="file"> </input>
						</div>
					</div>
					<p class="up-tips">從個人電腦選擇要上傳的文檔:按住CTRL能夠上傳多份文檔</p>
				</div>
			</div>
		</div>

輸入圖片說明 第二步:點擊上傳文檔按鈕確認選中文檔開始上傳apache

觸發 file_up_onclick事件調用js方法
        $scope.file_up_onclick=function(){
	    //1.獲取文件對象
		var _file=document.getElementById("file");
	    //2.實例化FormData對象
                   var $$fd=new FormData();
            //3.添加文件對象到FormData中
		$$fd.append("file",_file.files[0]);
            //4.開始異步上傳
		$http({
			method:'post',
			data: $$fd,
			url:'//servlet/FileCommand',
			headers: {'Content-Type':undefined},
 			/*序列化 formdata object*/
  			transformRequest: angular.identity 		
		}).success(function(data){	
		});
	};

第四步:servelt接收二進制文件 public class FileCommand extends HttpServlet{後端

// 1.文件上傳路徑
	private static final String UPLOAD_DIRECTORY = "D:/文件上傳";
	// 2.設置臨時存儲文件大小,當超過大小時,將先存儲超出大小文件在臨時目錄
	private static final int MEMORY_THRESHOLD = 1024 * 1024 * 30; 
	// 3.設置最大文件上傳值
	private static final int MAX_FILE_SIZE = 1024 * 1024 * 2000; 
	// 4.最大請求值
	private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 2048; 
	
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {

  doPost(request, response);
}

/**
 * @摘要 提供文件上傳的方法
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
	//1.設置字符編碼爲utf-8
	request.setCharacterEncoding("utf-8");
	response.setCharacterEncoding("utf-8");
	response.setContentType("text/html;charset=utf-8");
	// 2.檢測是否爲多媒體上傳
	if (!ServletFileUpload.isMultipartContent(request)) {
		// 2.1若是不是則中止
		PrintWriter writer = response.getWriter();
		writer.println("Error: 表單必須包含 enctype=multipart/form-data");
		writer.flush();
		return  ;
	}
	// 3.配置上傳參數
	DiskFileItemFactory factory = new DiskFileItemFactory();
	//4. 設置內存臨界值 - 超事後將產生臨時文件並存儲於臨時目錄中
	factory.setSizeThreshold(MEMORY_THRESHOLD);
	// 5.設置臨時存儲目錄 java.io.tmpdir默認的臨時文件路徑爲服務器的temp目錄
	factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

	ServletFileUpload upload = new ServletFileUpload(factory);

	// 6.設置最大文件上傳值
	upload.setFileSizeMax(MAX_FILE_SIZE);

	// 7.設置最大請求值 (包含文件和表單數據)
	upload.setSizeMax(MAX_REQUEST_SIZE);

	//8. 若是目錄不存在則建立
	File uploadDir = new File(UPLOAD_DIRECTORY);
	if (!uploadDir.exists()) {
		uploadDir.mkdir();
	}
	try {
		// 10.解析請求的內容提取文件數據
		List<FileItem> formItems = upload.parseRequest(request);
		System.out.println("name="+request.getSession().getAttribute("name"));
			// 10.1迭表明單數據
		if (formItems != null && formItems.size() > 0) {
			for (FileItem item : formItems) {
				if (!item.isFormField()){
					String nFileName = new File(item.getName()).getName();
					
					String nPrefix=nFileName.substring(nFileName.lastIndexOf(".")+1);
			       
					nFileName=nFileName.substring(0,nFileName.lastIndexOf("."))	;				
					
					item.write(new File(UPLOAD_DIRECTORY+"/"+nFileName));
					
					item.delete();
					
			        PrintWriter nWriter=response.getWriter();
			        
			        nWriter.print("{\"prefix\":\""+nPrefix+"\",\"filename\":\""+nFileName+"\",\"filesize\":\""+item.getSize()+"\"}");
                }
				}
			}  
	} catch (Exception ex) {
		PrintWriter writer=response.getWriter();
		writer.print("error");
	}

}服務器

第五步:查看文件是否在指定目錄便可app

相關文章
相關標籤/搜索