Web front-end fragment upload demo (based on webuploader)

First, briefly explain the principle of resuming the transfer from a breakpoint:

     The client selects the file, performs MD5 through webuploader, and then performs sharding. Each shard needs to be checked before uploading (checking that the current shard has already been uploaded). In the merge operation, all shards are merged in sequence in the background, and a file is generated according to the specified file name.

1. Preparation:

     1) The front end uses jquery (jquery-1.10.2.js), webuploader plugin (webuploader-0.1.5)

     2) Prepare springMvc in the background (use annotations, configure requestMapping)

    3) Development environment jsp, MyEclipse 1.0

2. Development steps:

    1) Integrate springMvc, the steps here are relatively simple (you can follow: http://www.jianshu.com/p/0ccaa4af05fc ).

    2) Import jquery, webuploader, and write the front page, the code is as follows:

  

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ include file="/root/comm/jsp/tags.jsp"%>
<!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=GBK">
<title>Breakpoint resume</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript"	src="${ctx}/root/comm/js/jquery-1.10.2.js"></script>
<script type="text/javascript"	src="${ctx}/root/comm/webuploader-0.1.5/webuploader.js"></script>
<link rel="stylesheet" type="text/css"	href="${ctx}/root/comm/webuploader-0.1.5/webuploader.css">

<script type="text/javascript">
	// Monitor the time point of the block upload, and resume the upload from a breakpoint
	var fileMd5; //Save the file MD5 name
	var uploader; //global object uploader
	WebUploader.Uploader.register(
					{"before-send-file" : "beforeSendFile", //Execute before file upload
					 "before-send" : "beforeSend", //Execute before the file block is uploaded
					 "after-send-file" : "afterSendFile", //Execute after upload is complete
					},
					{
						//Time point 1: This function is called before all uploads are made
						beforeSendFile : function(file) {
							var deferred = WebUploader.Deferred();
							// Calculate the unique identifier of the file, which is used for breakpoint resuming and wonderful biography
							(new WebUploader.Uploader()).md5File(file, 0,
									10 * 1024 * 1024).progress(
									function(percentage) {
										$("#" + file.id).find("span.state").text("Getting file information...");
									}).then(
									function(val) {
										fileMd5 = val;
										$("#" + file.id).find("span.state").text("Successfully obtained file information");
										// release
										deferred.resolve();
									});
							return deferred.promise();
						},
						//Execute this operation before each block is sent to check whether the current block has been uploaded
						beforeSend : function(block) {
							var deferred = WebUploader.Deferred();
							$.ajax({
										type : "POST",
										url : "${ctx}/system/upload/testUploadMergeUploadFile.htm?action=checkChunk",
										data : {
											// file unique tag  
											fileMd5 : fileMd5,
											// current block subscript  
											chunk : block.chunk,
											// current chunk size  
											chunkSize : block.end - block.start
										},
										dataType : "json",
										success : function(response) {
											if (response.ifExist) {
												//The block exists, skip it  
												deferred.reject();
											} else {
												//The block does not exist or is incomplete, resend the content of the block  
												deferred.resolve();
											}
										}
									});
							this.owner.options.formData.fileMd5 = fileMd5;
							return deferred.promise();
						},
						afterSendFile : function(file) {
							// Notify merge chunks
							 $.ajax({
									type : "POST",
									url : "/RenWei/system/upload/testUploadMergeUploadFile.htm?action=mergeChunks",
									data : {
										'fileMd5' : fileMd5
									},
									success : function(response) {
										var $ li = $ ('#' + file.id);
										$li.find('p.state').text('Upload complete');
										$("#ctlBtn").addClass('disabled');
									}
									});
						}
					});

	$(function() {
		// upload basic configuration
		uploader = WebUploader.create({
			swf : "${ctx}/root/comm/webuploader-0.1.5/Uploader.swf",
			server : '${ctx}/system/upload/testUploadSaveFile.htm',
			pick : "#filePicker",
			car: false,
			// Chunk upload settings
			// whether to block
			chunked : true,
			// The size of each file (default 5M)
			chunkSize : 10 * 1024 * 1024,
			// Open several non-threads (default 3)
			threads : 1,
			// While uploading the current file, prepare the next file
			formData : { //You can customize attributes here, all of which can be received in the background
				fileMd5 : fileMd5
			},
			prepareNextFile : true
		});

		// Triggered when the file is selected
		uploader.on("fileQueued", function(file) {
			// Append the file information to the div of fileList
			$("#fileList").append(
					'<div id="' + file.id + '" class="item">'
							+ '<h4 class="info">' + file.name + '</h4>'
							+ '<p class="state">Waiting for upload...</p>' + '</div>');
			//md5 calculation
			uploader.md5File(file).progress(function(percentage) {
				console.log('Percentage:', percentage);
			})
			// Finish
			.then(function(md5File) { // done
				fileMd5 = md5File;
				$('#' + file.id).find('p.state').text('MD5 is calculated, you can click to upload');
				$("#ctlBtn").removeClass('disabled');
				
			});
		});

		// Monitor upload progress
		// percentage: represents the percentage of uploaded files
		// Real-time display of the creation progress bar during the file upload process.
		uploader.on('uploadProgress', function(file, percentage) {
			var $ li = $ ('#' + file.id);
			$li.find('p.state').text('Uploading'+Math.round(percentage * 100) + '%');
		});

		$("#ctlBtn").on('click', function() {
			if ($(this).hasClass('disabled')) {
				alert("Please select a file or wait for the file to generate MD5.");
				return false;
			}
			uploader.options.formData['fileMd5'] = fileMd5;
			uploader.upload ();
		});
	});
</script>
</head>
<body>
	<!-- 2. Create page elements -->
	<div id="upload">
		<div id="fileList"></div>
		<div id="filePicker" style="float: left;">选择文件</div>
		<button id="ctlBtn" class="btn btn-default disabled" style="padding: 8px 15px;">开始上传</button>
		<div class="statusBar" style="display: none;">
			<div class="progress">
				<span class="text">0%</span> <span class="percentage"></span>
			</div>
			<div class="info"></div>
		</div>
	</div>
</body>
</html>

 -------------------------------------------------- --------------- Gorgeous dividing line ------------------------------- -------------------

 

So far the front-end code has been completed:

  3) Start writing the background code:

 

@Controller
@RequestMapping("/system/upload")
public class TestUpload {
	
	String serverPath = "d:\\"; //Temporary directory
	/*
	 * Save file, data block
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("testUploadSaveFile.htm")
	public void saveFile(HttpServletRequest request,
			HttpServletResponse response) {
		
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		
		try {
			List<FileItem> items = upload.parseRequest(request);
			
			UploadUtil.saveChunkData(items);
			
		} catch (FileUploadException e) {
			
			e.printStackTrace ();
		}
	}
	
	//Merge uploaded files
	@RequestMapping("testUploadMergeUploadFile.htm")
	public void mergeUploadFile(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("Enter merge background...");
        
        String action = request.getParameter("action");
        String saveFilePath = ConfigUtil.getInstance().getProValue("saveChunkFilePath");
    	String fileMd5 = request.getParameter("fileMd5");
    	
        if("mergeChunks".equals(action)){
        	
        	UploadUtil.mergeUploadFile(saveFilePath, fileMd5);
        }
        else if("checkChunk".equals(action)){
            // current block subscript
            String chunk = request.getParameter("chunk");
            // current chunk size
            String chunkSize = request.getParameter("chunkSize");
           String yesOrNoFlag =  UploadUtil.checkChunk(saveFilePath+"/"+fileMd5, chunk, chunkSize);
           
           if(yesOrNoFlag.equals("1")){
        	   response.getWriter().write("{\"ifExist\":"+yesOrNoFlag+"}");
        	   }
           else{
        	   response.getWriter().write("{\"ifExist\":"+yesOrNoFlag+"}");
           }
           }
        }
}

    I have abstracted the specific upload method ( UploadUtil.mergeUploadFile(saveFilePath, fileMd5), UploadUtil.saveChunkData(items)) in the above code.

),

 

    code show as below: 

       Yo, the abstraction is still placed in the attachment (UploadUtil.java), so that you can copy it directly if you want to use it. ^_^^_^^_^^_^^_^

 

 

Well, it is unknown so far that all our work has been completed, we can directly publish the code on the middleware, and directly view what we have just written.

jsp.

 

Under normal circumstances, the upload can be successful, and there is a progress bar showing the progress of the upload.

 

If unsuccessful, please follow the steps below to check:

  1.WebUploader.Uploader.register (1.2.3) The three methods must be placed at the front, and cannot be placed in $(function(){...})

, the three methods of 1.2.3 do not take effect because of the scope chain problem.

  2. Multiple uploads of the same shard still cover the problem, release after each shard check is completed, block the method problem, deferred.reject();

deferred.resolve(); Mainly, the deferred deferred object is released regardless of the result after the check is completed. Solution: Strictly follow the writing in my code, there is no problem.

 

Finally, if you still have any problems, such as finding logical errors in the code that are not rigorous enough, you can contact me directly.

WeChat: ma0603kang

 

Guess you like

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