巧用 Jersey RESTful WebService框架解決文件上傳亂碼

1、當咱們使用jersey框架封裝的restful進行文件上傳時,會出現中文亂碼,試用了過濾器設置編碼都無論用。仔細想了好久解決辦法,就用一個servelt來代替這個上傳的restful接口實現上傳的邏輯。

2、不事後來對restful設計風格和jersey底層的初步研究,發現其實能夠使用jersey做爲入口來接收文件流,處理仍是用apache提供的commons-fileupload-1.3.1.jar來實現,內部request請求設置
編碼,就不會出現文件亂碼

3、前端依舊是angular封裝百度提供的webupload指令實現文件的上傳和分片存儲

4、邏輯以下

前端


<!DOCTYPE html>
<html>
<head>
<title>柳絮飛祭奠</title>

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../plugins/webuploader/webuploader.css"
	type="text/css"></link>
</head>
<body class="lx_droparea">
<lx-upload droparea="lx_droparea" id="upload" type="button"  value="上傳" style="width:80px;"></lx-ui-upload>
</body>
<script type="text/javascript" src="../plugins/jquery.js"></script>
<script type="text/javascript" src="../plugins/angular.min.js"></script>
<script type="text/javascript"
	src="../plugins/webuploader/webuploader.min.js"></script>

<script type="text/javascript">
//設置lx.upload的配置信息
	var $$runtime = {file:'/JerseyTest/api/1.0/my/upload', "swf":"",debug : true};

	var lxUpload=angular.module("lx.upload",[]);
	
/**
 * 
 * 
 */
lxUpload.directive('lxUpload',function(){
	var option = {
		restrict : 'E',
		replace : true,
		template : '<div>上傳文件</div>',
		scope:true,
		link : function($scope, $element, $attrs) {
		//聲明做用域內上傳數據對象
		$scope.upload={"id":"","droparea":"","md5":"","length":0,"data":[],"tip":true,"isupload":false};
		//設置上傳文件id
		$scope.upload.id="#"+$attrs.id;
		$scope.upload.droparea="."+$attrs.droparea;
		WebUploader.Uploader.register({
			"before-send-file" : "beforeSendFile"
		}, {
			// 時間點1:全部分塊進行上傳以前調用此函數
			beforeSendFile : function(file) {
				var deferred = WebUploader.Deferred();
				// 一、使用md5計算文件的惟一標記,用於斷點續傳
				uploader.md5File(file).then(function(val) {
					$scope.upload.md5= val;
					console.log($scope.upload.md5);
					// 2.1.5延遲解決
					deferred.resolve();
				});
				return deferred.promise();
			},
		});
		var uploader = WebUploader.create({
			// swf文件路徑
			swf : $$runtime.swf,
			// 文件接收服務端。
			server : $$runtime.file,
			// 選擇文件的按鈕。可選。
			// 內部根據當前運行是建立,多是input元素,也多是flash.
			pick : {
				id : $scope.upload.id,
				// 這個id是你要點擊上傳文件的id,本身設置就好</span>
				multiple : true
			},
			// 不壓縮image, 默認若是是jpeg,文件上傳前會壓縮一把再上傳!
			resize : true,
			dnd:$scope.upload.droparea,
			auto : true,
			// 上傳併發數
			threads : 5,
			// 開啓分片上傳
			chunked : true,
			chunkSize : 1 * 1024 * 1024,
            duplicate :true  
		});
//		// 聲明WebUploader內【uploadBeforeSend】事件
//		uploader.on("beforeFileQueued", function(file) {
//			if(!$scope.upload.isupload){
//				$$alert("請選擇文件夾",3);	
//				return false;
//			}
//		});
		// 聲明WebUploader內【uploadBeforeSend】事件
		uploader.on("fileQueued", function(block, data) {
			if($scope.upload.tip){
			}
			$scope.upload.length++;
			// wenbuploader添加攜帶參數
		});
		// 聲明WebUploader內【uploadBeforeSend】事件
		uploader.on("uploadBeforeSend", function(block, data) {
			// wenbuploader添加攜帶參數
			console.log($scope.upload.md5);
			data.fileMd5 = $scope.upload.md5;
		});
		// 聲明WebUploader內【uploadSuccess】事件
		uploader.on("uploadSuccess", function(file, response) {
			$scope.upload.data.push(response[0]);
			$scope.upload.length--;
			if($scope.upload.length==0){
				$scope.$emit('upload', $scope.upload.data);	
				$scope.upload.data=[];
					}
				});
			}
		};	
		return option;
	});
	 //啓動應用程序
    angular.bootstrap(document,['lx.upload']);
</script>
</html>


後端


@POST
	@Path("/upload")
	@Produces({ MediaType.APPLICATION_JSON + ";charset=UTF-8" })
	public String upload(@Context HttpServletRequest request)
			throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		// 獲取或設置md5值
		String nFileMd5 = null;
		// 獲取或設置分片數值
		String nChunk = "0";
		// 文件地址拿去到配置中
		File dir = new File(WebConfig.MAIN_UPLOAD_PATH);
		if (!dir.exists()) {
			if (!dir.mkdirs()) {
				throw new RuntimeException("Directory "
						+ WebConfig.MAIN_UPLOAD_PATH
						+ " not exists and can not create directory.");
			}
		}
		File nDirCACHE_PATH = new File(WebConfig.MAIN_UPLOAD_CACHE_PATH);
		if (!nDirCACHE_PATH.exists()) {
			if (!nDirCACHE_PATH.mkdirs()) {
				throw new RuntimeException("Directory "
						+ WebConfig.MAIN_UPLOAD_CACHE_PATH
						+ " not exists and can not create directory.");
			}
		}
		// 驗證上傳內容了類型
		String contentType = request.getContentType();
		if ((contentType.indexOf("multipart/form-data") >= 0)) {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// 設置內存中存儲文件的最大值
			factory.setSizeThreshold(WebConfig.MAIN_UPLOAD_MAXSIZE);
			factory.setSizeThreshold(WebConfig.MAIN_UPLOAD_MEMORY_THRESHOLD);
			// 設置緩存路徑
			factory.setRepository(new File(WebConfig.MAIN_UPLOAD_CACHE_PATH));
			// 建立一個新的文件上傳處理程序
			ServletFileUpload upload = new ServletFileUpload(factory);
			// 設置最大上傳的文件大小
			upload.setFileSizeMax(WebConfig.MAIN_UPLOAD_MAXSIZE);
			upload.setSizeMax(WebConfig.MAIN_UPLOAD_MAX_REQUEST_SIZE);

			try {
				// 解析獲取的文件
				List<FileItem> formItems = upload.parseRequest(request);
				for (FileItem file : formItems) {
					if (file.isFormField()) {
						String fieldName = file.getFieldName();
						if (fieldName.equals("fileMd5")) {
							// 10.2.1.獲取md5值
							nFileMd5 = file.getString("utf-8");
						}
						if (fieldName.equals("chunk")) {
							// 10.2.2.獲取分片數值
							nChunk = file.getString("utf-8");
						}
					} else {
						Map<String, Object> nFileMap = new HashMap<String, Object>();
						String nFileName = file.getName();
						File nFile = new File(WebConfig.MAIN_UPLOAD_PATH
								+ File.separator + nFileMd5);
						if (!nFile.exists()) {
							nFile.mkdir();
						}
						file.write(new File(WebConfig.MAIN_UPLOAD_PATH
								+ File.separator + nFileMd5 + File.separator
								+ nChunk));
						if (file.isInMemory()) {
							file.delete();
						}
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "";
	}


ending  附件帶示例
相關文章
相關標籤/搜索