1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8" %> 2 <%@ taglib prefix="s" uri="/struts-tags" %> 3 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 4 5 <!DOCTYPE HTML PUBLIC "-//W3C//Dtd HTML 4.01 transitional//EN"> 6 <html> 7 <head> 8 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 9 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 10 <meta http-equiv="pragma" content="no-cache"> 11 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 12 <meta http-equiv="cache-control" content="no-cache"> 13 <meta http-equiv="expires" content="0"> 14 15 <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.8.0.min.js"></script> 22 <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-ui-1.11.4/jquery-ui.min.js"></script> 23 <link rel="stylesheet" href="${pageContext.request.contextPath}/js/jquery-ui-1.11.4/jquery-ui.css" type="text/css" /> 24 <link rel="stylesheet" href="${pageContext.request.contextPath}/js/plupload-2.1.8/js/jquery.ui.plupload/css/jquery.ui.plupload.css" type="text/css" /> 25 <!-- production --> 26 <script type="text/javascript" src="${pageContext.request.contextPath}/js/plupload-2.1.8/js/plupload.full.min.js"></script> 27 <script type="text/javascript" src="${pageContext.request.contextPath}/js/plupload-2.1.8/js/jquery.ui.plupload/jquery.ui.plupload.js"></script> 28 29 <script type="text/javascript" src="${pageContext.request.contextPath}/js/plupload-2.1.8/js/i18n/zh_CN.js"></script> 30 31 <title>TEST</title> 32 </head> 33 <body> 34 <div class="container"> 35 <div class="progress progress-striped active"> 36 <div class="progress-bar" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100" style="width: 50%;"></div> 37 </div> 38 <h1 class="text-center">申请表信息填写</small></h1> 39 <br> 40 <form id="form" action="upload_FileAction" method="POST" enctype="multipart/form-data" > 41 42 43 <div id="uploader"> 44 <p>您的浏览器未安装 Flash, Silverlight, Gears, BrowserPlus 或者支持 HTML5 .</p> 45 </div> 46 <br /> 47 48 <ul id="file-list"> </ul> 49 <input type="button" class="btn btn-lg btn-primary" id="submitBtn" onclick="submitForm()" value="提交"/> 50 <button onclick="javascript:window.history.back()" class="btn btn-lg btn-primary" type="button">返回</button> 51 <Br><br> 52 </form> 53 </div> 54 </body> 55 </html>
upload.jsp页面
JS文件
1 // Convert divs to queue widgets when the DOM is ready 2 $(function() { 3 $("#uploader").plupload({ 4 // General settings 5 runtimes : 'html5,flash,silverlight,html4', 6 // url : "FileUpload.action", 7 url : "./uploadImg.action?Id="+$("#Id").val(), 8 // Maximum file size 9 max_file_size : '500kb', 10 // User can upload no more then 10 files in one go (sets multiple_queues to false) 11 chunk_size: '1mb', 12 max_file_count: 10, 13 // Resize images on clientside if we can 14 resize : { 15 width : 320, 16 height : 240, 17 quality : 90, 18 crop: true // crop to exact dimensions 19 }, 20 21 // Specify what files to browse for 22 filters : { 23 prevent_duplicates : true, //不允许选取重复文件 24 // Specify what files to browse for 25 mime_types: [ 26 {title : "Image files", extensions : "jpeg,jpg,gif,png"} 27 ] 28 }, 29 30 // Rename files by clicking on their titles 31 rename: true, 32 33 // Sort files 34 sortable: true, 35 36 // Enable ability to drag'n'drop files onto the widget (currently only HTML5 supports that) 37 dragdrop: true, 38 39 // Views to activate 40 views: { 41 list: true, 42 thumbs: true, // Show thumbs 43 active: 'thumbs' 44 }, 45 46 // Flash settings 47 flash_swf_url : '${pageContext.request.contextPath}/js/plupload-2.1.8/js/Moxie.swf', 48 49 // Silverlight settings 50 silverlight_xap_url : '${pageContext.request.contextPath}/js/plupload-2.1.8/js/Moxie.xap', 51 // PreInit events, bound before any internal events 52 preinit : { 53 Init: function(up, info) { 54 //log('[Init]', 'Info:', info, 'Features:', up.features); 55 //// document.getElementById('uploadfiles').onclick = function() { 56 // $("#uploader").plupload.start(); 57 // return false; 58 // }; 59 $('#uploader_start').hide(); 60 }, 61 UploadFile: function(up, file) { 62 // log('[UploadFile]', file); 63 up.setOption('url', './uploadImg.action?Id='+$('#Id').val()); 64 // You can override settings before the file is uploaded 65 // up.setOption('url', 'upload.php?id=' + file.id); 66 // up.setOption('multipart_params', {param1 : 'value1', param2 : 'value2'}); 67 } 68 }, 69 // Post init events, bound after the internal events 70 init : { 71 BeforeUpload: function(up, file) { 72 // Called right before the upload for a given file starts, can be used to cancel it if required 73 //log('[BeforeUpload]', 'File: ', file); 74 }, 75 FilesAdded: function(up, files) { 76 // Called when files are added to queue 77 //log('[FilesAdded]'); 78 //plupload.each(files, function(file) { 79 /// log(' File:', file); 80 //// }); 81 for(var i = 0, len = files.length; i<len; i++){ 82 var file_name = files[i].name; //文件名 83 //构造html来更新UI 84 var html = '<li id="file-' + files[i].id +'"><p class="file-name">' + file_name + '</p><p class="progress"></p></li>'; 85 $(html).appendTo('#file-list'); 86 !function(i){ 87 previewImage(files[i],function(imgsrc){ 88 $('#file-'+files[i].id).append('<img src="'+ imgsrc +'" />'); 89 }); 90 }(i); 91 } 92 }, 93 FilesRemoved: function(up, files) { 94 // Called when files are removed from queue 95 plupload.each(files, function(file) { 96 $('#file-'+file.id).remove(); 97 98 }); 99 }, 100 FileUploaded: function(up, file, info) { 101 // Called when file has finished uploading 102 }, 103 UploadComplete: function(up, files) { 104 // Called when all files are either uploaded or failed 105 //alert("上传完成!共"+files.length+"个。成功"+files.length); 106 } 107 } 108 }); 109 }); 110 // Handle the case when form was submitted before uploading has finished 111 function submitForm() { 112 var form = document.forms[0]; 113 if(validate(form)){// 114 // Files in queue upload them first 115 if ($('#uploader').plupload('getFiles').length > 0) { 116 117 // When all files are uploaded submit form 118 $('#uploader').on('complete', function(up,files) { 119 //$('#form')[0].submit(); 120 $("form:eq(0)").submit(); 121 }); 122 123 $('#uploader').plupload('start'); 124 } else { 125 alert("请至少选择一张图片上传。"); 126 } 127 } 128 return false; // Keep the form from submitting 129 130 } 131 //plupload中为我们提供了mOxie对象 132 //有关mOxie的介绍和说明请看:https://github.com/moxiecode/moxie/wiki/API 133 //如果你不想了解那么多的话,那就照抄本示例的代码来得到预览的图片吧 134 function previewImage(file,callback){//file为plupload事件监听函数参数中的file对象,callback为预览图片准备完成的回调函数 135 if(!file || !/image\//.test(file.type)) return; //确保文件是图片 136 if(file.type=='image/gif'){//gif使用FileReader进行预览,因为mOxie.Image只支持jpg和png 137 var fr = new mOxie.FileReader(); 138 fr.onload = function(){ 139 callback(fr.result); 140 fr.destroy(); 141 fr = null; 142 }; 143 fr.readAsDataURL(file.getSource()); 144 }else{ 145 var preloader = new mOxie.Image(); 146 preloader.onload = function() { 147 preloader.downsize( 300, 300 );//先压缩一下要预览的图片,宽300,高300 148 var imgsrc = preloader.type=='image/jpeg' ? preloader.getAsDataURL('image/jpeg',80) : preloader.getAsDataURL(); //得到图片src,实质为一个base64编码的数据 149 callback && callback(imgsrc); //callback传入的参数为预览图片的url 150 preloader.destroy(); 151 preloader = null; 152 }; 153 preloader.load( file.getSource() ); 154 } 155 }
struts.xml
<action name="upload_*" class="cn.cttic.action.FileAction" method="{1}"> <interceptor-ref name="fileUpload"> <param name="allowedTypes"> <!-- image/bmp,image/png,image/gif,image/jpeg,image/jpg,image/x-png, image/pjpeg ,application/octet-stream --> </param> <param name="maximumSize">5242880</param><!-- 5242880 --> </interceptor-ref> <!-- 默认的拦截器,必须要写 --> <interceptor-ref name="defaultStack" /> <result name="ok">/test/upload.jsp</result> </action>
Java代码
1 private File file; 2 private String name; 3 private List<String> names; 4 private String fileFileName; 5 //文件类型 6 private String fileContentType; 7 //大文件上传 分块chul 8 private int chunk; 9 private int chunks; 10 private String Id; 11 12 public String uploadImg() throws IOException { 13 String path = FileConfiguration.IMAGES_TEMP_PATH;//d:/var/images/temp/ 14 Date now = new Date(); 15 path = path+ Id + "/"; 16 File dir = new File(path); 17 if (!dir.exists()) { 18 dir.mkdirs(); 19 } 20 // 把图片写入到上面设置的路径里,并设置图片URL路径 21 String targetFileName = path + Id + "-" + now.getTime() 22 + getExtention(fileFileName); 23 imageFileName.add(targetFileName); 24 File target = new File(targetFileName); 25 FileCopyUtils.copy(file, target); 26 return SUCCESS; 27 }
plupload是一款优秀的web前端上传框架,使用简单,功能强大,不仅支持文件多上传,进度条,拖拽方式选择文件更重要的是他会自动的识别浏览器来选择最合适的上传方式,
http://www.cnblogs.com/2050/p/3913184.html#plupload_doc4
http://blog.csdn.net/u014754818/article/details/46800709
http://www.cnblogs.com/God-Shell/articles/3209708.html
测试demo:
http://jsfiddle.net/noo4je7w/
官网API:
http://www.plupload.com/docs/API