文章出處
View Code
View Code
文章列表
Plupload 是一個Web瀏覽器上的界面友好的文件上傳模塊,可顯示上傳進度、圖像自動縮略和上傳分塊。可同時上傳多個文件;
上網找了很多Plupload的DEMO都無法正常使用, 而且Plupload官方的DEMO是基于PHP, 折騰了半天, 寫了一個基于JAVA的DEMO;
Plupload支持多種方式上傳, 包括,flash上傳(解決了不同服務器跨域的問題), html5方式上傳, html4上傳, silverlight的方式上傳, Plupload的核心是另外一個JS庫:
MOXIE, MOXIE提供了Plupload的運行環境, 也可以單獨拿出來使用, 代碼量(體積)挺大的,MOXIE提供了下面幾種上傳環境:
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() { } }
前端界面的主要代碼:

<%@ 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>
整體界面如下:
文章列表
全站熱搜