jQuery plupload 的使用
Plupload 是一个Web浏览器上的界面友好的文件上传模块,可显示上传进度、图像自动缩略和上传分块。可同时上传多文件,拖拽,图像缩略等功能。
docs:http://www.plupload.com/examples/core
github: https://github.com/zhouyongtao/my-plupload
HTML:
<%@ 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> <link rel="stylesheet" href="${pageContext.request.contextPath}/jslib/plupload_1_5_7/plupload/js/jquery.plupload.queue/css/jquery.plupload.queue.css" type="text/css"></link> <script type="text/javascript" src="${pageContext.request.contextPath}/jslib/jquery-1.8.3.js"></script> <script type="text/javascript" src="${pageContext.request.contextPath}/jslib/plupload_1_5_7/plupload/js/plupload.full.js"></script> <script type="text/javascript" src="${pageContext.request.contextPath}/jslib/plupload_1_5_7/plupload/js/jquery.plupload.queue/jquery.plupload.queue.js"></script> <script type="text/javascript" src="${pageContext.request.contextPath}/jslib/plupload_1_5_7/plupload/js/i18n/zh-CN.js"></script> <script type="text/javascript"> $(function() { $("#uploader").pluploadQueue({ runtimes : 'html5,flash,silverlight',//设置运行环境,会按设置的顺序,可以选择的值有html5,gears,flash,silverlight,browserplus,html4 flash_swf_url : '${pageContext.request.contextPath}/jslib/plupload_1_5_7/plupload/js/plupload.flash.swf',// Flash环境路径设置 silverlight_xap_url : '${pageContext.request.contextPath}/jslib/plupload_1_5_7/plupload/js/plupload.silverlight.xap',//silverlight环境路径设置 url : '${pageContext.request.contextPath}/UploadServlet',//上传文件路径 max_file_size : '3gb',//100b, 10kb, 10mb, 1gb chunk_size : '1mb',//分块大小,小于这个大小的不分块 unique_names : true,//生成唯一文件名 // 如果可能的话,压缩图片大小 // resize : { width : 320, height : 240, quality : 90 }, // 指定要浏览的文件类型 filters : [ { title : 'Image files', extensions : 'jpg,gif,png' }, { title : 'Zip files', extensions : 'zip,7z,rar' } ], init : { FileUploaded : function(up, file, info) {//文件上传完毕触发 console.info(up); console.info(file); console.info(info); var response = $.parseJSON(info.response); if (response.status) { $('#f1').append('<input type="hidden" name="fileUrl" value="'+response.fileUrl+'"/>'); $('#f1').append('<input type="hidden" name="fileName" value="'+file.name+'"/><br/>'); } } } }); // 客户端表单验证 $('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('请选择至少一个文件进行上传!'); } return false; }); }); </script> </head> <body> <form id="f1" action="${pageContext.request.contextPath}/DemoAction" method="post"> <table border="1"> <tr> <td colspan="2"> <div id="uploader">您的浏览器没有安装Flash插件,或不支持HTML5!</div> <!-- <button onclick="$('#uploader').pluploadQueue().start();">开始上传</button> <button onclick="$('#uploader').pluploadQueue().stop();">停止上传</button> --> </td> </tr> <tr> <th>姓名</th> <td><input name="name" value="Irving" /></td> </tr> <tr> <th>密码</th> <td><input name="pwd" value="123456" /></td> </tr> </table> <button type="submit">提交表单</button> </form> </body> </html>
JAVA:
package sy.util.base; 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.ServletException; import javax.servlet.http.HttpServlet; 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 com.alibaba.fastjson.JSON; public class UploadServlet extends HttpServlet { String uploadPath; private static final ResourceBundle bundle = ResourceBundle .getBundle("config"); public UploadServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setCharacterEncoding("UTF-8"); Integer chunk = null;// 分割块数 Integer chunks = null;// 总分割数 String tempFileName = null;// 临时文件名 String newFileName = null;// 最后合并后的新文件名 BufferedOutputStream outputStream = null; 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(); } } } } @Override public void init(ServletConfig config) throws ServletException { //System.out.println(FileUtils.getTempDirectoryPath()); uploadPath = config.getServletContext().getRealPath( bundle.getString("uploadPath")); File up = new File(uploadPath); if (!up.exists()) { up.mkdir(); } } }
Refer:
http://www.51aspx.com/code/pluploadNetDemo
http://weblog.west-wind.com/posts/2013/Mar/12/Using-plUpload-to-upload-Files-with-ASPNET
http://blog.cdeutsch.com/2011/02/plupload-and-aspnet-mvc3.html
http://blog.cdeutsch.com/2011/02/plupload-and-aspnet-mvc3.html