webuploader in springMVC+jquery+Java development environment large file sharding upload example code

  • 2020-07-21 07:33:11
  • OfStack

Note:

1. webuploader upload component will conflict with jQuery's own upload component, so don't use it < form > Add the attributes of the upload file in the tag;


enctype="multipart/form-data"

2. And block es11EN-ES12en. xml inside the interception configuration!


<!--  Upload interception, such as maximum and minimum upload values  --> 
  <!-- The increase of webuploader Upload component , You have to block the interception mechanism here  
   <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >   
     <property name="maxUploadSize">   
       <value>1073741824</value>   
      </property>   
      <property name="maxInMemorySize">   
        <value>1073741824</value>   
      </property>   
       <property name="defaultEncoding">   
        <value>utf-8</value>   
      </property>  
  </bean>  
  --> 

The front and back code development starts now:

1. Call the webuploader component's public file in the page jsp file


<link rel="stylesheet" href="static/css/webuploader.css" rel="external nofollow" /> 

<script type="text/javascript" src="static/js/webuploader.js"></script> 
    <script type="text/javascript" src="static/js/webuploader.min.js"></script> 
    <script type="text/javascript" src="static/js/upload3.js"></script> 

Control code on the page:


<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> 

Since I used automatic upload, I annotated the upload button, and es28EN3.js also annotated the corresponding click method of the upload button.

2. The real upload component code is upload3.ES33en, which introduces the initialization, sharding and various parameters of webuploader. You can refer to API on the official website for details


/*********************************WebUpload  Single file upload  begin*****************************************/ 
$(function(){ 
  var $list = $("#thelist"); 
  var uploader ;//  instantiation    
  uploader = WebUploader.create({  
      auto:true, // Whether to upload automatically  
      pick: { 
        id: '#attach', 
        name:"multiFile", // This place  name  It doesn't help, and fileVal  Cooperate to use.  
        label: ' I'm gonna go ahead and select the file , It will automatically upload ', 
        multiple:false // The default is true . true Means you can select multiple files, HTML5 The properties of the  
      }, 
      swf: '../Uploader.swf', // I have to introduce here swf File, webuploader Initializers are used  
      fileVal:'multiFile', // Submit to the background, is to use "multiFile" This name attribute is used to fetch the file  
      server: "myPractice/webUploader.do", 
      duplicate:true,// Whether the same can be repeatedly selected 1 file  
      resize: false, 
      chunked: true, // Shard processing  
      chunkSize: 20 * 1024 * 1024, // Each piece 20M 
      chunkRetry:2,// If it fails, don't try again  
      threads:1,// Number of concurrent uploads. Maximum number of simultaneous uploads allowed.  
      fileNumLimit:1,// Total number of files uploaded  
      //  Disable global drag and drop functionality.  
      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'> Are uploading ...</p>" + 
      "</div>" ); 
    }); 
    // Triggered when all file uploads are finished  
    uploader.on("uploadFinished",function(){ 
      console.log("uploadFinished:"); 
    }) 
    // Triggered when the file is uploaded successfully.  
    uploader.on( "uploadSuccess", function( file ,response) { 
//     alert(file.name); 
      $( "#"+file.id ).find("p.state").text(" uploaded "); 
    }); 
    uploader.on( "uploadError", function( file ) { 
      $( "#"+file.id ).find("p.state").text(" Upload error "); 
      uploader.cancelFile(file); 
      uploader.removeFile(file,true); 
      uploader.reset(); 
    }); 
    // If you upload it manually , Use the following event , And enable the jsp The upload button on the page  
//    $("#upload").on("click", function() { 
//      uploader.upload(); 
//    }) 
}); 
/*********************************WebUpload  Single file upload  end*******************************************/ 

3. After the foreground is completed, the background Java code needs to be found to realize the function of uploading to the server. The server attribute in the webuploader component refers to the server-side code:


@Controller 
@RequestMapping(value="/myPractice")<span style="font-family: Arial, Helvetica, sans-serif;">// So this is just saying how does the upload component get through server Property to find the back end code , Don't worry too much about the details </span> 
public class MyPracticeController extends BaseController { 
<span> </span> 
@RequestMapping(method = {RequestMethod.POST}, value = {"/webUploader"}) 
@ResponseBody 
public void webUploader(HttpServletRequest request, HttpServletResponse response) throws Exception { 
  try { 
      boolean isMultipart = ServletFileUpload.isMultipartContent(request); 
      if (isMultipart) { 
        FileItemFactory factory = new DiskFileItemFactory(); 
        ServletFileUpload upload = new ServletFileUpload(factory); 
        //  Get all the form fields that are currently treated as FileItem 
        List<FileItem> fileItems = upload.parseRequest(request); 
        String id = ""; 
        String fileName = ""; 
        //  If more than 1 Description is shard processing  
        int chunks = 1; 
        int chunk = 0; 
        FileItem tempFileItem = null; 
        for (FileItem fileItem : fileItems) { 
          if (fileItem.getFieldName().equals("id")) { 
            id = fileItem.getString(); 
          } else if (fileItem.getFieldName().equals("name")) { 
            fileName = new String(fileItem.getString().getBytes("ISO-8859-1"), "UTF-8"); 
          } else if (fileItem.getFieldName().equals("chunks")) { 
            chunks = NumberUtils.toInt(fileItem.getString()); 
          } else if (fileItem.getFieldName().equals("chunk")) { 
            chunk = NumberUtils.toInt(fileItem.getString()); 
          } else if (fileItem.getFieldName().equals("multiFile")) { 
            tempFileItem = fileItem; 
          } 
        } 
        //session "Is my own reason , You can just use the file name fileName, This is the original file name  
        String fileSysName = this.getRequest().getSession().getAttribute("fileSysName").toString(); 
        String realname = fileSysName+fileName.substring(fileName.lastIndexOf("."));// The converted file name  
        this.getRequest().getSession().setAttribute("realname",realname); 
        String filePath = Const.VIDEOPATHFILE + "sound/";// File upload path  
        //  A temporary directory is used to store all sharded files  
        String tempFileDir = filePath + id; 
        File parentFileDir = new File(tempFileDir); 
        if (!parentFileDir.exists()) { 
          parentFileDir.mkdirs(); 
        } 
        //  When shard processing, the foreground will call the upload interface several times, each time will upload the file 1 Part to background  
        File tempPartFile = new File(parentFileDir, realname + "_" + chunk + ".part"); 
        FileUtils.copyInputStreamToFile(tempFileItem.getInputStream(), tempPartFile); 
        //  Whether all uploads have been completed  
        //  All shards exist before the entire file is uploaded  
        boolean uploadDone = true; 
        for (int i = 0; i < chunks; i++) { 
          File partFile = new File(parentFileDir, realname + "_" + i + ".part"); 
          if (!partFile.exists()) { 
            uploadDone = false; 
          } 
        } 
        //  All sharding files have been uploaded  
        //  Merge all shard files into 1 A file  
        if (uploadDone) { 
          //  get  destTempFile  It's the final document  
          File destTempFile = new File(filePath, realname); 
          for (int i = 0; i < chunks; i++) { 
            File partFile = new File(parentFileDir, realname + "_" + i + ".part"); 
            FileOutputStream destTempfos = new FileOutputStream(destTempFile, true); 
            // traverse " All sharding files " to " The final file " In the  
            FileUtils.copyFile(partFile, destTempfos); 
            destTempfos.close(); 
          } 
          //  Deletes sharding files in a temporary directory  
          FileUtils.deleteDirectory(parentFileDir); 
        } else { 
          //  Temporary file creation failed  
          if (chunk == chunks -1) { 
            FileUtils.deleteDirectory(parentFileDir); 
          } 
        } 
      } 
    } catch (Exception e) { 
      logger.error(e.getMessage(), e); 
    } 
} 

That's about it. That's all the code that webuploader has designed in the front and back,

Uploader.swf


<pre name="code" class="html">webuploader.min.js</pre><pre name="code" class="html"><pre name="code" class="html">webuploader.js</pre><pre name="code" class="html">webuploader.css</pre><pre name="code" class="html"> this 4 The public files can be downloaded from the official website , all 1 sample .
<pre name="code" class="plain"> The last , The page style is after the file is uploaded </pre><pre name="code" class="plain"><pre name="code" class="html"><img src="http://img.blog.csdn.net/20170418112230338?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvd2FuZ2xvbmcxOTkwNDIx/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt=""> 
</pre> 
<pre></pre> 
<pre></pre> 
<pre></pre> 
<pre></pre> 
<p></p> 
<pre></pre> 
<pre></pre> 
<pre></pre> 
<pre></pre> 
<pre></pre> 
<pre></pre> 
<pre></pre> 
<pre></pre> 
</pre></pre></pre> 

Related articles: