Written before:
In the past few days, I have studied the upload of WebUploader files. The previous blog records examples of using WebUploader to simply upload files. Today, I will also record the examples of uploading fragments and breakpoints. In the blog park, I have also viewed some information. Basically, the backend processing of data is Servlets or SpringMVC. Since the recent project has always been Struts2, we will use the action in Struts2 to process the data to achieve the effect of uploading files in pieces.
1.What is shard upload?
As the name suggests, it means dividing the file into pieces, that is, letting a file be divided into several small files, and then uploading it. The advantage of this is that it facilitates uploading large files.
2. General ideas for shard uploading:
1. On the front desk page, select the file and click the button to upload.
2. WebUploader divides the uploaded files into specified numbers and sends them to the server backend one by one.
3. The server receives the divided small files and stores them in a temporary folder.
4. After the server receives the divided small file, the foreground page executes the upload successful function.
5. In the upload successful function, send a request to the server and request to merge the small files into a whole file.
6. The server background merges the files and deletes the temporary files that store small files after the merge is completed.
After understanding the general process of shard uploading, please go to demo directly.
Front Desk Page:
<%@ page contentType="text/html;charset=UTF-8" language="java" %><% String scheme = request.getScheme(); String serverName = request.getServerName(); String contextPath = request.getContextPath(); int port = request.getServerPort(); //Website access and path String baseURL = scheme + "://" + serverName + ":" + port + contextPath; request.setAttribute("baseURL", baseURL);%><html><head> <title> Simple example of uploading files with fragmented </title> <%--Introducing css styles--%> <link href="${baseURL}/webuploader0.1.5/webuploader.css" rel="external nofollow" rel="stylesheet" type="text/css"/> <script src="${baseURL}/ligerui2/jquery/jquery-1.9.0.min.js" type="text/javascript"></script> <%-Introducing file upload plugin--%> <script type="text/javascript" src="${baseURL}/webuploader0.1.5/webuploader.min.js"></script> <script type="text/javascript"> $(function(){ /* For the creation of uploader, it is best to wait until the dom element is created, that is, the following div is created, because the button to select the file is used, otherwise an error will be created. This is a place that is easy to ignore. Therefore, you put $(function(){} here to create */ var uploader = WebUploader.create({ // swf file path swf: '${baseURL}/webuploader0.1.5/Uploader.swf', // File receiving server address. server: '${baseURL}/uploadFile2', // [Default: 'file'] Sets the name of the file upload domain. fileVal:'upload', // Select the file button. Optional. // Created internally according to the current run, which may be an input element or flash. pick: { multiple: false, id: '#filePicker' }, // Number of upload concurrents. The maximum number of upload processes allowed at the same time [Default: 3] That is, the number of uploaded files/* This is the key. If shard upload is enabled, it will not limit the number of uploads at the same time, it will cause the shards accepted by the background to be inconsistent. For example, according to the normal shard, the first slice should be the beginning, but the received one may become the third slice, and the order is inconsistent. This is because Baidu webuploader allows the maximum number of upload processes at the same time by default, so it will cause the order of acceptance and errors to reorganize. Therefore, it is set to 1*/ threads: 1, // Automatic upload is modified to manually upload auto: false, // Do you want to handle large file uploads? Chunked: true, // If you want to slice, how big a slice is? The default size is 5M. chunkSize: 5 * 1024 * 1024, // No image is compressed, default if it is jpeg, it will compress and upload it again before uploading! resize: false, formData: { guid: Math.random() //This is mainly used to name temporary folders that store small files} }); //When a file is added, uploader.on('fileQueued', function (file) { //Reselect the file and clear $("#fileList").html(""); //Written the specific logic according to the project requirements. Let me give you a simple example to write $one = $("<div id='"+file.id+"'>"+file.name+"</div>"); $two = $("<div id='state'>wait for uploading....</div>"); $("#fileList").append($one); $("#fileList").append($two); }); // Create a progress bar in real time during file uploading. uploader.on('uploadProgress', function (file, percentage) { // Specific logic... console.log("uploadProgress===="+percentage); $("#state").text("uploading..."); }); // File upload is successfully processed. uploader.on('uploadSuccess', function (file, response) { // Specific logic... console.log('upload success.../n'); console.log(uploader.options.formData.guid); console.log(file.name); // Merge file $.post( "${baseURL}/mergeFile", //System { guid: uploader.options.formData.guid, chunks: Math.ceil(file.size / (5 * 1024 * 1024)), fileName: file.name }, function(data){ }); $("#state").text("File upload successfully~~~"); }); // File upload failed processing. uploader.on('uploadError', function (file) { // Specific logic... }); // After uploading and uploading are completed, this event will be called regardless of success or failure. It is mainly used to close the progress bar uploader.on('uploadComplete', function (file) { // Specific logic... }); //Click the upload button to trigger the event $("#btnClick").click(function(){ uploader.upload(); }); //Cancel upload $("#btnCancel").click(function(){ //Logistic processing.. }); }); </script></head><body style="padding:10px"><div id="layout1"> <div id="uploader-demo"> <div id="fileList" >Select file</div> <button id="btnClick">Start upload</button> <button id="btnCancel">Cancel Upload</button> </div></div></body></html>Backend action:
/** * Description:com.ims.action * Author: Eleven * Date: 2017/12/26 10:50 */@Controller("FileAction")public class FileAction { /*Related parameters for each small file used to receive segmentation request*/ //Remember to provide the corresponding get set method//Upload file object (the same as the name value of form type=file) private File upload; //File name private String uploadFileName; //Upload type private String uploadContentType; /** * The following variables are public, there are too many parameters, so I don't want to set it to private and then write the get and set method, * Just use public just by lazy */ //File sharding number public String chunk; public String guid;//Merge and split are both used for receiving and sending merge requests public String fileName; //File name public String chunks; //Segment number//When uploading files in shards, this method will be called every time a small file is uploaded, which is no different from ordinary saving files public void uploadFile2() throws Exception{ String str = "D:/upload44/divide/"; //File saving path//Save the path of each small file String realPath = str + guid +"/" + chunk; File tmp =new File(realPath); FileUtils.copyFile(upload, tmp); System.out.println("Upload file"+uploadFileName+", which block: "+chunk+", size: "+(upload.length()/1024/1024)+"M"); } //File merge public void mergeFile() throws Exception{ String path = "D:/upload44/merge/" ; //Create merge folder new File(path).mkdir(); //Create merged file File newFile = new File(path + fileName); if(!newFile.exists()){ newFile.createNewFile(); } FileOutputStream outputStream = new FileOutputStream(newFile, true);//Add file append to byte[] byt = new byte[10 * 1024 * 1024]; int len; FileInputStream temp = null;//Shash file for (int i = 0; i < Integer.parseInt(chunks); i++) { //"D:/upload44/divide/" + guid + "/" + i To save the path of the divided small file temp = new FileInputStream(new File("D:/upload44/divide/" + guid + "/" + i)); while ((len = temp.read(byt)) != -1) { System.out.println(len); outputStream.write(byt, 0, len); } temp.close(); } //When all append writes are finished, the stream can be closed outputStream.close(); //Delete shard file String path2 = "D:/upload44/divide/" + guid; FileUtils.deleteDirectory(new File(path2));//Delete all contents in the directory System.out.println("success!guid=" + guid + ";chunks=" + chunks + ";fileName=" + fileName); } public File getUpload() { return upload; } public void setUpload(File upload) { this.upload = upload; } public String getUploadFileName() { return uploadFileName; } public void setUploadFileName(String uploadFileName) { this.uploadFileName = uploadFileName; } public String getUploadContentType() { return uploadContentType; } public void setUploadContentType(String uploadContentType) { this.uploadContentType = uploadContentType; }}Struts.xml configuration:
<action name="uploadFile2" method="uploadFile2"></action><action name="mergeFile" method="mergeFile"></action>
OK, here, uploading a simple file fragmentation breakpoint is completed.
By the way, the background only receives some simple parameters, and of course there are more than the above parameters passed from the front-end WebUploader. Therefore, you can learn to use F12 debugging mode to view the sent requests and related request parameters. I won't talk about it here.
Running screenshot:
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.