plupload+struts2实现文件上传下载

时间:2022-03-16 22:55:43
 <%@ page language="java" import="java.util.*" pageEncoding="utf-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE HTML PUBLIC "-//W3C//Dtd HTML 4.01 transitional//EN">
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0"> <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.8.0.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-ui-1.11.4/jquery-ui.min.js"></script>
<link rel="stylesheet" href="${pageContext.request.contextPath}/js/jquery-ui-1.11.4/jquery-ui.css" type="text/css" />
<link rel="stylesheet" href="${pageContext.request.contextPath}/js/plupload-2.1.8/js/jquery.ui.plupload/css/jquery.ui.plupload.css" type="text/css" />
<!-- production -->
<script type="text/javascript" src="${pageContext.request.contextPath}/js/plupload-2.1.8/js/plupload.full.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/plupload-2.1.8/js/jquery.ui.plupload/jquery.ui.plupload.js"></script> <script type="text/javascript" src="${pageContext.request.contextPath}/js/plupload-2.1.8/js/i18n/zh_CN.js"></script> <title>TEST</title>
</head>
<body>
<div class="container">
<div class="progress progress-striped active">
<div class="progress-bar" role="progressbar" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100" style="width: 50%;"></div>
</div>
<h1 class="text-center">申请表信息填写</small></h1>
<br>
<form id="form" action="upload_FileAction" method="POST" enctype="multipart/form-data" > <div id="uploader">
<p>您的浏览器未安装 Flash, Silverlight, Gears, BrowserPlus 或者支持 HTML5 .</p>
</div>
<br /> <ul id="file-list"> </ul>
<input type="button" class="btn btn-lg btn-primary" id="submitBtn" onclick="submitForm()" value="提交"/>
<button onclick="javascript:window.history.back()" class="btn btn-lg btn-primary" type="button">返回</button>
<Br><br>
</form>
</div>
</body>
</html>

upload.jsp页面

JS文件

 // Convert divs to queue widgets when the DOM is ready
$(function() {
$("#uploader").plupload({
// General settings
runtimes : 'html5,flash,silverlight,html4',
// url : "FileUpload.action",
url : "./uploadImg.action?Id="+$("#Id").val(),
// Maximum file size
max_file_size : '500kb',
// User can upload no more then 10 files in one go (sets multiple_queues to false)
chunk_size: '1mb',
max_file_count: 10,
// Resize images on clientside if we can
resize : {
width : 320,
height : 240,
quality : 90,
crop: true // crop to exact dimensions
}, // Specify what files to browse for
filters : {
prevent_duplicates : true, //不允许选取重复文件
// Specify what files to browse for
mime_types: [
{title : "Image files", extensions : "jpeg,jpg,gif,png"}
]
}, // Rename files by clicking on their titles
rename: true, // Sort files
sortable: true, // Enable ability to drag'n'drop files onto the widget (currently only HTML5 supports that)
dragdrop: true, // Views to activate
views: {
list: true,
thumbs: true, // Show thumbs
active: 'thumbs'
}, // Flash settings
flash_swf_url : '${pageContext.request.contextPath}/js/plupload-2.1.8/js/Moxie.swf', // Silverlight settings
silverlight_xap_url : '${pageContext.request.contextPath}/js/plupload-2.1.8/js/Moxie.xap',
// PreInit events, bound before any internal events
preinit : {
Init: function(up, info) {
//log('[Init]', 'Info:', info, 'Features:', up.features);
//// document.getElementById('uploadfiles').onclick = function() {
// $("#uploader").plupload.start();
// return false;
// };
$('#uploader_start').hide();
},
UploadFile: function(up, file) {
// log('[UploadFile]', file);
up.setOption('url', './uploadImg.action?Id='+$('#Id').val());
// You can override settings before the file is uploaded
// up.setOption('url', 'upload.php?id=' + file.id);
// up.setOption('multipart_params', {param1 : 'value1', param2 : 'value2'});
}
},
// Post init events, bound after the internal events
init : {
BeforeUpload: function(up, file) {
// Called right before the upload for a given file starts, can be used to cancel it if required
//log('[BeforeUpload]', 'File: ', file);
},
FilesAdded: function(up, files) {
// Called when files are added to queue
//log('[FilesAdded]');
//plupload.each(files, function(file) {
/// log(' File:', file);
//// });
for(var i = 0, len = files.length; i<len; i++){
var file_name = files[i].name; //文件名
//构造html来更新UI
var html = '<li id="file-' + files[i].id +'"><p class="file-name">' + file_name + '</p><p class="progress"></p></li>';
$(html).appendTo('#file-list');
!function(i){
previewImage(files[i],function(imgsrc){
$('#file-'+files[i].id).append('<img src="'+ imgsrc +'" />');
});
}(i);
}
},
FilesRemoved: function(up, files) {
// Called when files are removed from queue
plupload.each(files, function(file) {
$('#file-'+file.id).remove(); });
},
FileUploaded: function(up, file, info) {
// Called when file has finished uploading
},
UploadComplete: function(up, files) {
// Called when all files are either uploaded or failed
//alert("上传完成!共"+files.length+"个。成功"+files.length);
}
}
});
});
// Handle the case when form was submitted before uploading has finished
function submitForm() {
var form = document.forms[0];
if(validate(form)){//
// Files in queue upload them first
if ($('#uploader').plupload('getFiles').length > 0) { // When all files are uploaded submit form
$('#uploader').on('complete', function(up,files) {
//$('#form')[0].submit();
$("form:eq(0)").submit();
}); $('#uploader').plupload('start');
} else {
alert("请至少选择一张图片上传。");
}
}
return false; // Keep the form from submitting }
//plupload中为我们提供了mOxie对象
//有关mOxie的介绍和说明请看:https://github.com/moxiecode/moxie/wiki/API
//如果你不想了解那么多的话,那就照抄本示例的代码来得到预览的图片吧
function previewImage(file,callback){//file为plupload事件监听函数参数中的file对象,callback为预览图片准备完成的回调函数
if(!file || !/image\//.test(file.type)) return; //确保文件是图片
if(file.type=='image/gif'){//gif使用FileReader进行预览,因为mOxie.Image只支持jpg和png
var fr = new mOxie.FileReader();
fr.onload = function(){
callback(fr.result);
fr.destroy();
fr = null;
};
fr.readAsDataURL(file.getSource());
}else{
var preloader = new mOxie.Image();
preloader.onload = function() {
preloader.downsize( 300, 300 );//先压缩一下要预览的图片,宽300,高300
var imgsrc = preloader.type=='image/jpeg' ? preloader.getAsDataURL('image/jpeg',80) : preloader.getAsDataURL(); //得到图片src,实质为一个base64编码的数据
callback && callback(imgsrc); //callback传入的参数为预览图片的url
preloader.destroy();
preloader = null;
};
preloader.load( file.getSource() );
}
}

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代码

     private File file;
private String name;
private List<String> names;
private String fileFileName;
//文件类型
private String fileContentType;
//大文件上传 分块chul
private int chunk;
private int chunks;
private String Id; public String uploadImg() throws IOException {
String path = FileConfiguration.IMAGES_TEMP_PATH;//d:/var/images/temp/
Date now = new Date();
path = path+ Id + "/";
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
// 把图片写入到上面设置的路径里,并设置图片URL路径
String targetFileName = path + Id + "-" + now.getTime()
+ getExtention(fileFileName);
imageFileName.add(targetFileName);
File target = new File(targetFileName);
FileCopyUtils.copy(file, target);
return SUCCESS;
}

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