转载

Plupload上传组件 + javaweb实现上传源码以及DEMO

Plupload 是一个Web浏览器上的界面友好的文件上传模块,可显示上传进度、图像自动缩略和上传分块。可同时上传多个文件;

上网找了很多Plupload的DEMO都无法正常使用, 而且Plupload官方的DEMO是基于PHP, 折腾了半天, 写了一个基于JAVA的DEMO;

Plupload支持多种方式上传, 包括,flash上传(解决了不同服务器跨域的问题), html5方式上传, html4上传, silverlight的方式上传, Plupload的核心是另外一个JS库:

MOXIE, MOXIE提供了Plupload的运行环境, 也可以单独拿出来使用, 代码量(体积)挺大的,MOXIE提供了下面几种上传环境:

Plupload上传组件 + javaweb实现上传源码以及DEMO

Plupload支持分块上传, 支持拖拽上传, 支持图片切块, 支持30多种语言, 而且提供了丰富的API, 因为支持多种方式上传, 可以比较放心的使用这个JS插件;

容器是tomcat, 需要java的spring框架, 需要apache的几个jar包, commons.fileupload等....;

以下代码是处理文件上传的java代码:

  package controller;  import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import java.util.UUID;  import javax.servlet.ServletConfig; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;  import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody;  import com.alibaba.fastjson.JSON;  @Controller public class mainController {      String uploadPath;     private static final ResourceBundle    bundle = ResourceBundle.getBundle( "config" );          @RequestMapping(value="uploadFile.do", method=RequestMethod.POST)     public void uploadFile( HttpServletRequest request, HttpServletResponse response   ) throws IOException {          response.setCharacterEncoding( "UTF-8" );         Integer chunk = null; /* 分割块数 */         Integer chunks = null; /* 总分割数 */         String tempFileName = null; /* 临时文件名 */         String newFileName = null; /* 最后合并后的新文件名 */         BufferedOutputStream    outputStream    = null;                    /* System.out.println(FileUtils.getTempDirectoryPath()); */         uploadPath = request.getServletContext().getRealPath( bundle.getString( "uploadPath" ) );         File up = new File( uploadPath );         if ( !up.exists() )         {             up.mkdir();         }                  if ( ServletFileUpload.isMultipartContent( request ) )         {             try {                 DiskFileItemFactory factory = new DiskFileItemFactory();                 factory.setSizeThreshold( 1024 );                 /* factory.setRepository(new File(repositoryPath));// 设置临时目录 */                 ServletFileUpload upload = new ServletFileUpload( factory );                 upload.setHeaderEncoding( "UTF-8" );                 /* upload.setSizeMax(5 * 1024 * 1024);// 设置附件最大大小,超过这个大小上传会不成功 */                 List<FileItem> items = upload.parseRequest( request );                 for ( FileItem item : items )                 {                     if ( item.isFormField() ) /* 是文本域 */                     {                         if ( item.getFieldName().equals( "name" ) )                         {                             tempFileName = item.getString();                             /* System.out.println("临时文件名:" + tempFileName); */                         } else if ( item.getFieldName().equals( "chunk" ) )                         {                             chunk = Integer.parseInt( item.getString() );                             /* System.out.println("当前文件块:" + (chunk + 1)); */                         } else if ( item.getFieldName().equals( "chunks" ) )                         {                             chunks = Integer.parseInt( item.getString() );                             /* System.out.println("文件总分块:" + chunks); */                         }                     } else { /* 如果是文件类型 */                         if ( tempFileName != null )                         {                             String chunkName = tempFileName;                             if ( chunk != null )                             {                                 chunkName = chunk + "_" + tempFileName;                             }                             File savedFile = new File( uploadPath, chunkName );                             item.write( savedFile );                         }                     }                 }                  newFileName = UUID.randomUUID().toString().replace( "-", "" )                           .concat( "." )                           .concat( FilenameUtils.getExtension( tempFileName ) );                 if ( chunk != null && chunk + 1 == chunks )                 {                     outputStream = new BufferedOutputStream(                         new FileOutputStream( new File( uploadPath, newFileName ) ) );                     /* 遍历文件合并 */                     for ( int i = 0; i < chunks; i++ )                     {                         File tempFile = new File( uploadPath, i + "_" + tempFileName );                         byte[] bytes = FileUtils.readFileToByteArray( tempFile );                         outputStream.write( bytes );                         outputStream.flush();                         tempFile.delete();                     }                     outputStream.flush();                 }                 Map<String, Object> m = new HashMap<String, Object>();                 m.put( "status", true );                 m.put( "fileUrl", bundle.getString( "uploadPath" ) + "/"                        + newFileName );                 response.getWriter().write( JSON.toJSONString( m ) );             } catch ( FileUploadException e ) {                 e.printStackTrace();                 Map<String, Object> m = new HashMap<String, Object>();                 m.put( "status", false );                 response.getWriter().write( JSON.toJSONString( m ) );             } catch ( Exception e ) {                 e.printStackTrace();                 Map<String, Object> m = new HashMap<String, Object>();                 m.put( "status", false );                 response.getWriter().write( JSON.toJSONString( m ) );             } finally {                 try {                     if ( outputStream != null )                         outputStream.close();                 } catch ( IOException e ) {                     e.printStackTrace();                 }             }         }     }          public void main() {              }      }  View Code

前端界面的主要代码:

  <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>plupload示例</title> <script src="http://cdn.bootcss.com/jquery/1.9.0/jquery.js"></script> <script type="text/javascript" src="${pageContext.request.contextPath}/js/plupload.full.min.js"></script>  </head> <body>     <div id="filelist">          </div>     <button id="uploader">选择文件</button>     <div id="progress"></div>     <div id="result"></div> </body> <script type="text/javascript">         var uploader = new plupload.Uploader({             runtimes : 'html5,flash,silverlight',//设置运行环境,会按设置的顺序,可以选择的值有html5,gears,flash,silverlight,browserplus,html             flash_swf_url : './js/Moxie.swf',             silverlight_xap_url : './js/Moxie.xap',             url : '${pageContext.request.contextPath}/uploadFile.do',//上传文件路径             max_file_size : '3gb',//100b, 10kb, 10mb, 1gb             chunk_size : '1mb',//分块大小,小于这个大小的不分块             unique_names : true,//生成唯一文件名             browse_button : 'uploader',              filters : [ {                 title : 'Image files',                 extensions : 'jpg,gif,png'             }, {                 title : 'Zip files',                 extensions : 'zip,7z,rar'             } ],                          init : {                 FilesAdded: function(up, files) {                                      uploader.start();                     return false;                 },                 FileUploaded : function(up, file, info) {//文件上传完毕触发                     console.log("单独文件上传完毕");                     var response = $.parseJSON(info.response);                     if (response.status) {                         $('#result').append( $('<div> "文件路径是:"' + response.fileUrl + '"随机的文件名字为:"' + file.name + '</div>') );                     }                 },                 UploadComplete : function( uploader,files ) {                     console.log("所有文件上传完毕");                 },                 UploadProgress : function( uploader,file ) {                     $("#progress").html("上传进度为:" + file.percent + "%");                     console.log( file.percent );                 }             }         });                  uploader.init(); </script> </html>  View Code

整体界面如下:

Plupload上传组件 + javaweb实现上传源码以及DEMO

整体代码放在baidu云盘: 打开下载

github项目

plupload中文文档

百度网盘链接

正文到此结束
Loading...