Using Jersey RESTful WebService framework to solve garbled file uploading

1. When we use the restful packaged by the jersey framework to upload files, there will be Chinese garbled characters, and the filter setting encoding will not work. After thinking about the solution for a long time, I used a servelt to replace the uploading restful interface to implement the uploading logic.

2. However, after preliminary research on the restful design style and the bottom layer of jersey, it was found that jersey can be used as the entry to receive the file stream. The processing is still realized by commons-fileupload-1.3.1.jar provided by apache, and the internal request request is set to
encode. , there will be no garbled files.

3. The front end is still angular encapsulates the webupload instruction provided by Baidu to achieve file upload and fragmented storage .

4. The logic is as follows:




<!DOCTYPE html>
<html>
<head>
<title>Little catkins pay tribute</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">
//Set the configuration information of 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>Upload file</div>',
		scope:true,
		link : function($scope, $element, $attrs) {
		//Upload the data object in the declaration scope
		$scope.upload={"id":"","droparea":"","md5":"","length":0,"data":[],"tip":true,"isupload":false};
		//Set the upload file id
		$scope.upload.id="#"+$attrs.id;
		$scope.upload.droparea="."+$attrs.droparea;
		WebUploader.Uploader.register({
			"before-send-file" : "beforeSendFile"
		}, {
			// Time 1: This function is called before all chunks are uploaded
			beforeSendFile : function(file) {
				var deferred = WebUploader.Deferred();
				// 1. Use md5 to calculate the unique mark of the file for resuming the transfer from a breakpoint
				uploader.md5File(file).then(function(val) {
					$scope.upload.md5= val;
					console.log($scope.upload.md5);
					// 2.1.5 Delay resolution
					deferred.resolve();
				});
				return deferred.promise();
			},
		});
		var uploader = WebUploader.create ({
			// swf file path
			swf : $$runtime.swf,
			// File receiving server.
			server : $$runtime.file,
			// Button to select file. Optional.
			// Internally created according to the current operation, it may be an input element or flash.
			pick : {
				id : $scope.upload.id,
				// This id is the id of the file you want to click to upload, just set it yourself</span>
				multiple : true
			},
			// Do not compress the image, if the default is jpeg, the file will be compressed before uploading!
			resize : true,
			dnd:$scope.upload.droparea,
			auto: true,
			// upload concurrency
			threads : 5,
			// Enable multipart upload
			chunked : true,
			chunkSize : 1 * 1024 * 1024,
            duplicate :true  
		});
// // Declare the [uploadBeforeSend] event in WebUploader
//		uploader.on("beforeFileQueued", function(file) {
//			if(!$scope.upload.isupload){
// $$alert("Please select a folder",3);	
//				return false;
//			}
//		});
		// Declare the [uploadBeforeSend] event in WebUploader
		uploader.on("fileQueued", function(block, data) {
			if($scope.upload.tip){
			}
			$scope.upload.length++;
			// wenbuploader adds carrying parameters
		});
		// Declare the [uploadBeforeSend] event in WebUploader
		uploader.on("uploadBeforeSend", function(block, data) {
			// wenbuploader adds carrying parameters
			console.log($scope.upload.md5);
			data.fileMd5 = $scope.upload.md5;
		});
		// Declare the [uploadSuccess] event in WebUploader
		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;
	});
	 // start the application
    angular.bootstrap(document,['lx.upload']);
</script>
</html>


rear end


@POST
	@Path("/upload")
	@Produces({ MediaType.APPLICATION_JSON + ";charset=UTF-8" })
	public String upload(@Context HttpServletRequest request)
			throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		// Get or set the md5 value
		String nFileMd5 = null;
		// Get or set the slice value
		String nChunk = "0";
		// The file address is taken to the configuration
		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.");
			}
		}
		// Verify that the uploaded content has a type
		String contentType = request.getContentType();
		if ((contentType.indexOf("multipart/form-data") >= 0)) {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			// Set the maximum value of files stored in memory
			factory.setSizeThreshold(WebConfig.MAIN_UPLOAD_MAXSIZE);
			factory.setSizeThreshold(WebConfig.MAIN_UPLOAD_MEMORY_THRESHOLD);
			// set cache path
			factory.setRepository(new File(WebConfig.MAIN_UPLOAD_CACHE_PATH));
			// Create a new file upload handler
			ServletFileUpload upload = new ServletFileUpload(factory);
			// Set the maximum upload file size
			upload.setFileSizeMax(WebConfig.MAIN_UPLOAD_MAXSIZE);
			upload.setSizeMax(WebConfig.MAIN_UPLOAD_MAX_REQUEST_SIZE);

			try {
				// Parse the obtained file
				List<FileItem> formItems = upload.parseRequest(request);
				for (FileItem file : formItems) {
					if (file.isFormField()) {
						String fieldName = file.getFieldName();
						if (fieldName.equals("fileMd5")) {
							// 10.2.1. Get md5 value
							nFileMd5 = file.getString("utf-8");
						}
						if (fieldName.equals("chunk")) {
							// 10.2.2. Get slice value
							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 "";
	}



Example of ending attachment

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326117360&siteId=291194637