wolaoreme 2013-07-19
最近发现一个非常牛的上传组件(http://www.plupload.com/documentation.php),前端根据浏览器不同选择使用Html5、 Gears, Silverlight, Flash, BrowserPlus来对文件进行客户端优化,比如大图片的压缩,大文件分块上传,简直是太牛了,还有上传进度条、多文件上传等。官方网 站:http://plupload.com/,下载的domo是php版本的,于是我弄了个java版本的,分享给大家,
前端js等文件去下载个domo就有了,后端使用到了commons-fileupload-1.2.2.jar这个包。
前端html:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>plupload</title> <!-- 配置界面上的css --> <link rel="stylesheet" type="text/css" href="plupload/jquery.plupload.queue/css/jquery.plupload.queue.css"> <script type="text/javascript" src="js/jquery-1.6.2.min.js"></script> <script type="text/javascript" src="plupload/plupload.full.js"></script> <script type="text/javascript" src="plupload/jquery.plupload.queue/jquery.plupload.queue.js"></script> <!-- 国际化中文支持 --> <script type="text/javascript" src="plupload/i18n/cn.js"></script> <script type="text/javascript"> /* Convert divs to queue widgets when the DOM is ready */ $(function(){ function plupload(){ $("#uploader").pluploadQueue({ // General settings runtimes : 'html5,gears,browserplus,silverlight,flash,html4', url : 'servlet/fileUpload', max_file_size : '10mb', unique_names: true, chunk_size: '2mb', // Specify what files to browse for filters : [ {title: "Image files", extensions: "jpg,gif,png"}, {title: "Zip files", extensions: "zip"} ], resize: {width: 640, height: 480, quality: 90}, // Flash settings flash_swf_url: 'plupload/plupload.flash.swf', // Silverlight settings silverlight_xap_url: 'plupload/plupload.silverlight.xap', // 参数 multipart_params: {'user': 'Rocky', 'time': '2012-06-12'} }); } plupload(); $('#Reload').click(function(){ plupload(); }); }); </script> <div style="width:750px; margin:0 auto"> <form id="formId" action="Submit.action" method="post"> <div id="uploader"> <p>您的浏览器未安装 Flash, Silverlight, Gears, BrowserPlus 或者支持 HTML5 .</p> </div> <input value="重新上传" id="Reload" type="button"> </form> </div>
后端
package com.rock; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItemIterator; import org.apache.commons.fileupload.FileItemStream; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.fileupload.util.Streams; public class FileUploadAction extends HttpServlet { private static final long serialVersionUID = 3447685998419256747L; private static final String RESP_SUCCESS = "{\"jsonrpc\" : \"2.0\", \"result\" : \"success\", \"id\" : \"id\"}"; private static final String RESP_ERROR = "{\"jsonrpc\" : \"2.0\", \"error\" : {\"code\": 101, \"message\": \"Failed to open input stream.\"}, \"id\" : \"id\"}"; public static final String JSON = "application/json"; public static final int BUF_SIZE = 2 * 1024; public static final String FileDir = "uploadfile/"; private int chunk; private int chunks; private String name; private String user; private String time; /** * Handles an HTTP POST request from Plupload. * * @param req The HTTP request * @param resp The HTTP response */ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String responseString = RESP_SUCCESS; boolean isMultipart = ServletFileUpload.isMultipartContent(req); if(isMultipart){ ServletFileUpload upload = new ServletFileUpload(); try { FileItemIterator iter = upload.getItemIterator(req); while (iter.hasNext()) { FileItemStream item = iter.next(); InputStream input = item.openStream(); // Handle a form field. if(item.isFormField()){ String fileName = item.getFieldName(); String value = Streams.asString(input); if("name".equals(fileName)){ this.name = value; }else if("chunks".equals(fileName)){ this.chunks = Integer.parseInt(value); }else if("chunk".equals(fileName)){ this.chunk = Integer.parseInt(value); }else if("user".equals(fileName)){ this.user = value; }else if("time".equals(fileName)){ this.time = value; } } // Handle a multi-part MIME encoded file. else { String fileDir = req.getSession().getServletContext().getRealPath("/")+FileDir; File dstFile = new File(fileDir); if (!dstFile.exists()){ dstFile.mkdirs(); } File dst = new File(dstFile.getPath()+ "/" + this.name); saveUploadFile(input, dst); } } } catch (Exception e) { responseString = RESP_ERROR; e.printStackTrace(); } } // Not a multi-part MIME request. else { responseString = RESP_ERROR; } if(this.chunk == this.chunks - 1){ System.out.println("用户:"+this.user); System.out.println("文件名称:"+this.name); System.out.println("上传时间:"+this.time); } resp.setContentType(JSON); byte[] responseBytes = responseString.getBytes(); resp.setContentLength(responseBytes.length); ServletOutputStream output = resp.getOutputStream(); output.write(responseBytes); output.flush(); } /** * Saves the given file item (using the given input stream) to the web server's * local temp directory. * * @param input The input stream to read the file from * @param dst The dir of upload */ private void saveUploadFile(InputStream input, File dst) throws IOException { OutputStream out = null; try { if (dst.exists()) { out = new BufferedOutputStream(new FileOutputStream(dst, true), BUF_SIZE); } else { out = new BufferedOutputStream(new FileOutputStream(dst), BUF_SIZE); } byte[] buffer = new byte[BUF_SIZE]; int len = 0; while ((len = input.read(buffer)) > 0) { out.write(buffer, 0, len); } } catch (Exception e) { e.printStackTrace(); } finally { if (null != input) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != out) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
plupload的方法说明
var uploadFiles = function( ) { //定义上传方法
var uploader = new plupload.Uploader({ //定义上传控件
runtimes: 'html5,flash,html4',
browse_button: 'btn_wordView', //添加文件的标签的ID
container: 'upload_contain', //
url: test.ashx, //后台cs文件
flash_swf_url: flash.swf, //flash文件
filters : [
{title : "Image files", extensions : "jpg,gif,png"} //过滤格式
],
multipart_params: { action: "uploadPhoto" } //传到后台的参数
});
uploader.init(function(up, params) { //初始化
});
$('#start').unbind("click").bind("click",function(e) { //点击提交按钮事件
if(uploader.files.length > 0) {
uploader.start(); //开始上传
e.preventDefault();
}
});
uploader.bind("FilesAdded", function(up, files) {
//添加文件事件绑定
//up 包涵Uploader的全部信息
//files 包涵这一次添加的所有文件的基本信息
});
uploader.bind("BeforeUpload", function(up, file) {
//点击上传提交后,上传前的事件
//up 包涵Uploader的全部信息
//file 准备上传的一个文件的基本信息
});
uploader.bind('UploadProgress', function(up, file) {
//点击上传提交后,上传前的事件完成后,执行正在上传事件
//up 包涵Uploader的全部信息
//file 正在上传的一个文件的基本信息
});
uploader.bind("Error", function(up, err) {
//当上传失败时,所触发的事件
});
uploader.bind("FilesRemoved", function(up, fileArray) {
//删除已添加的文件所触发的事件
});
uploader.bind("FileUploaded", function(up, file, obj) {
//完成一个文件上传
//up 包涵Uploader的全部信息
//file 刚刚上传成功的一个文件的基本信息
//obj 后台cs文件返回的基本信息
});
uploader.bind("UploadComplete", function(up, files) {
//全部文件上传完毕之后所触发的事件
//up 包涵Uploader的全部信息
//files 所上传的全部文件的基本信息
});
};
uploadFiles(option, data);//执行上传的方法。
Plupload支持技术:
1:Flash
2:Gears
3:HTML 5
4:Silverlight
5:BrowserPlus
6:HTML 4
plupload主要功能:
1:突破HTTP上传限制,可上传大文件,官方论坛中有讨论上传2G文件的应用。
2:多文件队列上传
3:图片自动生成缩略图
4:上传后自动生成唯一文件名
5:自定制UI
JS参数配置说明:
<script type="text/javascript">
$(function() {
$("#uploader").pluploadQueue({
runtimes : 'gears,flash,silverlight,browserplus,html5', // 这里是说用什么技术引擎,由于国内浏览器问题这里一般使用flash即可。其他的删除掉。
url : 'upload.php', // 服务端上传路径
max_file_size : '10mb', // 文件上传最大限制。
chunk_size : '1mb', // 上传分块每块的大小,这个值小于服务器最大上传限制的值即可。(文件总大小/chunk_size = 分块数)。
unique_names : true, // 上传的文件名是否唯一
resize : {width : 320, height : 240, quality : 90}, // 是否生成缩略图(仅对图片文件有效)。
filters : [
{title : "Image files", extensions : "jpg,gif,png"},
{title : "Zip files", extensions : "zip"}
], // 这个数组是选择器,就是上传文件时限制的上传文件类型
flash_swf_url : '/plupload/js/plupload.flash.swf', // plupload.flash.swf 的所在路径
silverlight_xap_url : '/plupload/js/plupload.silverlight.xap' // silverlight所在路径
});
// 这一块主要是防止在上传未结束前表带提交,具体大家可酌情修改编写
$('form').submit(function(e) {
var uploader = $('#uploader').pluploadQueue(); // 取得上传队列
if (uploader.files.length > 0) { // 就是说如果上传队列中还有文件
uploader.bind('StateChanged', function() {
if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {
$('form')[0].submit();
}
});
uploader.start();
} else {
alert('You must queue at least one file.');
}
return false;
});
});
</script>
由于参数过多大家可以到官方网站查看API参数说明。