1. Description of the reasons for using the webuploader plugin
I was cheated by the project I am doing now.
Let me first talk about my project architecture spring+struts2+mybatis+MySQL
Then what. It was agreed that it would be enough to upload according to 2G, so I used the ajaxFileUpload plug-in. Because I used this to upload images before, I used it directly when uploading the attachment.
Various codes and codes have been tested. There is no problem with uploading 2G files. The trick came. After the project was launched, the customer asked to upload 4G files, and there were even more than 20G. . Nani, you didn't say it earlier. . .
Under IE11, use the ajaxFileUpload.js plug-in to upload files that exceed 4G, and IE directly throws an exception. A message with arithmetic result exceeding 32 bits popup.
As shown in the figure below:
As an additional note, my system is 64-bit, 8G memory, Google browser and IE11 browser are all 32-bit. It is a problem to upload 8G using AjaxFileUpload under Google. No errors will be reported.
IE11 has more than 4G and it is wrong to report the above picture directly. no way. Change the plug-in.
2. Plugin selection
1. Stream upload plugin. stream is a plug-in to solve the problem of uploading files by different browsers. It is a combination of Uploadify's flash version and html5. Plugin address http://www.twinkling.cn/
The function is indeed very powerful, but the CSS style is fixed, which is very different from the progress bar style of my current project. Give up this plugin
2.Webuploader plugin. WebUploader is a simple modern file upload component mainly HTML5 and supplemented by FLASH developed by Baidu WebFE (FEX) team. In modern browsers, we can give full play to the advantages of HTML5, while not abandoning mainstream IE browsers, and continue to use the original FLASH runtime, and are compatible with IE6+, iOS 6+, and Android 4+. The same call method can be selected by users at will.
The use of large file fragmentation concurrent uploading greatly improves the efficiency of file uploading. Plugin address http://fex.baidu.com/webuploader/
This plugin can customize CSS styles. The functions are also very powerful, so I decisively adopted this plug-in.
3. WebUploader single file upload
I am using Webuploader version 0.1.5. Webuploader mainly slices large files on the client, such as sending requests for sharding every 5M, and receiving files from the background to merge files. There are two ways to merge files. The first is to pass all shards to the background and then merge them. This is to ensure that the sharding order is correct, and the second is to merge while sharding. I used the second one in the project. Uploading files using Web Uploader requires three resources: JS, CSS, and SWF.
1.Introduce JS files
<script type="text/javascript" src="../main/js/webuploader.js"></script><script type="text/javascript" src="../main/js/webuploader.min.js"></script>
2. Introduce CSS style
<link href="../main/css/webuploader.css" rel="stylesheet" type="text/css" />
3. Introduce SWF . SWF does not refer to it directly. Just specify the SWF path when the webUploader is initialized.
4.upload3.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja"><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /><meta http-equiv="Content-Language" content="ja" /><meta http-equiv="Content-Script-Type" content="text/javascript" /><meta http-equiv="Content-Style-Type" content="text/css" /><title>DEMO</title><link href="../main/css/stream-v1.css" rel="stylesheet" type="text/css" /><link href="../main/css/webuploader.css" rel="stylesheet" type="text/css" /><script type="text/javascript" src="../main/js/jquery-1.11.1.min.js"></script><script type="text/javascript" src="../main/js/jquery-2.1.4.min.js"></script><script type="text/javascript" src="../main/js/jquery-ui.min.js"></script><script type="text/javascript" src="../main/js/bootstrap-datepicker.min.js"></script><script type="text/javascript" src="../main/js/bootstrap-datepicker.min.js"></script><script type="text/javascript" src="../main/js/locales/bootstrap-datepicker.ja.min.js"></script><script type="text/javascript" src="../main/js/webuploader.js"></script><script type="text/javascript" src="../main/js/webuploader.min.js"></script><script type="text/javascript" src="../js/contents/upload3.js"></script><body><div id="uploader"><!-- Used to store file information--><div id="thelist"></div><div><div id="attach"></div><input type="button" value="upload" id="upload"/> </div></div><div id="uploader1"><!--- Used to store file information--><div id="thelist1"></div><div><div id="multi"></div><input type="button" value="upload" id="multiUpload"/> </div></div></body></html>
The picture is relatively simple, it looks like this
5.upload3.js
Including single file upload, multi-file upload, and multiple instances of webuploader
/************************************************************/$(function(){var $list = $("#thelist");var uploader ;// Instantiated uploader = WebUploader.create({ auto:false, // Whether to automatically upload pick: {id: '#attach',name:"file", // This place name It's useless. Although I opened the debugger, the name of the input has indeed been changed. However, the file cannot be retrieved when submitted to the background. If you want to customize the name attribute of the file, you still need to use it with fileVal. label: 'Click to select the image', multiple:false //Default is true, which means you can choose multiple },swf: '../../main/js/Uploader.swf', //fileVal:'multiFile', //Customize the name attribute of the file. The version I used is 0.1.5. Open the client debugger and found that the name of the generated input has not been changed. //The name is still the default file, but it is not useless. Although the client name has not changed, the multiFile object is used to retrieve the file when submitted to the background. The file cannot be retrieved when using the file // It is recommended that the author have time to change this place, it will kill people. server: "ContentsDetail!ajaxAttachUpload.action", duplicate:true,//Is the same file resize: false,formData: {"status":"file","contentsDto.contentsId":"0000004730","uploadNum":"0000004730","existFlg":'false'}, compress: null,//Image not compressed chunked: true, //Shash processing chunkSize: 5 * 1024 * 1024, //5M per slice chunkRetry:false,//If it fails, do not try threads:1,//Upload concurrent number. Maximum number of upload processes allowed at the same time. // runtimeOrder: 'flash', // Disable the global drag function. This will not appear when the image is dragged into the page, open the image. disableGlobalDnd: true}); // When a file is added, uploader.on( "fileQueued", function( file ) {console.log("fileQueued:");$list.append( "<div id='"+ file.id + "' class='item'>" +"<h4 class='info'>" + file.name + "</h4>" +"<p class='state'>Waiting for upload...</p>" +"</div>" );});// When all files are uploaded, uploader.on("uploadFinished", function(){console.log("uploadFinished:");})//When a file is uploaded to the server response, this event will be sent to ask whether the server response is valid. uploader.on("uploadAccept",function(object,ret){//The server responded //ret._raw is similar to datavar data =JSON.parse(ret._raw);if(data.resultCode != "1" && data.resultCode != "3"){if(data.resultCode == "9"){uploader.reset();alert("error");return false;}}else{//E05017uploader.reset();alert("error");return false;}})//Free when the file upload is successful. uploader.on( "uploadSuccess", function( file ) {$( "#"+file.id ).find("p.state").text("uploaded");});uploader.on( "uploadError", function( file ) {$( "#"+file.id ).find("p.state").text("uploader error");uploader.cancelFile(file);uploader.removeFile(file,true);uploader.reset();});$("#upload").on("click", function() {uploader.upload();})});/******************************************************WebUpload Single file upload end*********************************************//************************************************WebUpload Multi-file upload begin******************************************************//$(function(){var $list = $("#thelist1");var fileSize = 0; //Total file size var fileName = []; //File name list var fileSizeOneByOne =[];//Each file size var uploader ;//Instantiated uploader = WebUploader.create({ auto:false, //Whether to upload pick automatically: {id: '#multi',label: 'Click to select file',name:"multiFile"},swf: '../../main/js/Uploader.swf', server: "ContentsDetail!multiUpload.action", duplicate:true, //Is the same file resize: false,formData: {"status":"multi","contentsDto.contentsId":"0000004730","uploadNum":"0000004730","existFlg":'false'}, compress: null,//The picture is not compressed chunked: true, //Shash chunkSize: 5 * 1024 * 1024, //5MchunkRetry:false,//If it fails, do not try again threads:1,//Upload concurrent number. The maximum number of upload processes allowed at the same time. //fileNumLimit:50,//Verify the total number of files. If it exceeds it, it will not be allowed to join the queue.// runtimeOrder: 'flash', // Disable the global drag and drop function. This way, when the image is dragged into the page, open the image. disableGlobalDnd: true}); // When a file is added, uploader.on( "fileQueued", function( file ) {console.log("fileQueued:");$list.append( "<div id='"+ file.id + "' class='item'>" +"<h4 class='info'>" + file.name + "</h4>" +"<p class='state'>wait for upload...</p>" +"</div>" );}); // When the uploader is started, uploader.on( "startUpload", function() {console.log("startUpload");//Add additional form parameters $.extend( true, uploader.options.formData, {"fileSize":fileSize,"multiFileName":fileName.join(","),"fileSizeOneByOne":fileSizeOneByOne.join(",")}); });//After a file is uploaded to the server response, this event will be sent to ask whether the server response is valid. uploader.on("uploadAccept",function(object,ret){//The server responded //ret._raw is similar to dataconsole.log("uploadAccept");console.log(ret);var data =JSON.parse(ret._raw);if(data.resultCode!="1" && data.resultCode !="3"){if(data.resultCode == "9"){alert("error");uploader.reset();return;}}else{uploader.reset();alert("error");}})uploader.on( "uploadSuccess", function( file ) {$( "#"+file.id ).find("p.state").text("uploaded");});uploader.on( "uploadError", function( file,reason ) {$( "#"+file.id ).find("p.state").text("uploadError");console.log(file);console.log(reason);//Multiple files var fileArray = uploader.getFiles();for(var i = 0 ;i<fileArray.length;i++){uploader.cancelFile(fileArray[i]);uploader.removeFile(fileArray[i],true);}uploader.reset();fileSize = 0;fileName = [];fileSizeOneByOne=[];});//When validate fails, the caller will be notified in the form of a dispatch error event uploader.on("error",function(){console.log("error");uploader.reset();fileSize = 0;fileName = [];fileSizeOneByOne=[];alert("error");})//If it is the upload button in the modal box, the control will not be triggered when clicking the file //Fix the bug where the internal click of the model will not trigger the selected file/* $("#multi .webuploader-pick").click(function () {uploader.reset();fileSize = 0;fileName = [];fileSizeOneByOne=[];$("#multi :file").click();//Key code});*///Open the upload after selecting the file $(document).on("change","input[name='multiFile']", function() {var fileArray1 = uploader.getFiles();for(var i = 0 ;i<fileArray1.length;i++){//Use fileSize +=fileArray1[i].size;fileSizeOneByOne.push(fileArray1[i].size);fileName.push(fileArray1[i].name);}console.log(fileSize);console.log(fileSize);console.log(fileSizeOneByOne);console.log(fileName);})/*** Multi-file upload*/$("input[name='multiUpload']").on("click",function(){uploader.upload();})});/******************************************************WebUpload Multi-file upload end************************************************//****************************************************** The parameters of the webuploader are submitted to the background.********************************************************** {//web uploader The built-in parameters lastModifiedDate=[Wed Apr 27 2016 16:45:01 GMT+0800 (China Standard Time)], chunks=[3], chunk=[0], type=[audio/wav], uid=[yangl], id=[WU_FILE_0], size=[268620636], name=[3.wav], //formData parameters contentsDto.contentsId=[0000004730], existFlg=[false], status=[file], uploadNum=[0000004730]}******************************************************************************************************************************************/6.ContentsDetail.action
//Single file upload background code public void ajaxAttachUpload() {String path = "d://test//"+fileFileName;try {File file = this.getFile();FileUtil.randomAccessFile(path, file);//If the file is small and 5M, the value of the shard parameter chunk is nullif(StringUtils.isEmpty(chunk)){outJson("0", "success", "");}else{//chunk shard index, the subscript starts from 0//chunks Total shard count if (Integer.valueOf(chunk) == (Integer.valueOf(chunks) - 1)) {outJson("0", "uploaded successfully", "");} else {outJson("2", "uploading" + fileFileName + " chunk:" + chunk, "");}}} catch (Exception e) {outJson("3", "upload failed", "");}}FileUtil.java
/*** Specify the location to start writing the file* @param tempFile Input file* @param outPath Path to the output file (path + file name)* @throws IOException*/public static void randomAccessFile( String outPath,File tempFile) throws IOException{RandomAccessFile raFile = null;BufferedInputStream inputStream=null;try{File dirFile = new File(outPath);//Open the target file in read and write raFile = new RandomAccessFile(dirFile, "rw"); raFile.seek(raFile.length());inputStream = new BufferedInputStream(new FileInputStream(tempFile));byte[] buf = new byte[1024];int length = 0;while ((length = inputStream.read(buf)) != -1) {raFile.write(buf, 0, length);}}catch(Exception e){throw new IOException(e.getMessage());} finally{try {if (inputStream != null) {inputStream.close();}if (raFile != null) {raFile.close();}}catch(Exception e){throw new IOException(e.getMessage());}}} 7. Effect picture
The above is the relevant knowledge of the method of uploading large files, single files and multiple files in Java introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!