outsiderlcy 2014-07-15
1、 下载到官方网址下载“uploadify3.2”插件。
2、 下载swfobject_2_2js插件
3、 搭建struts2框架。
4、 创建upload2.jsp页面,内容如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>Jquery插件上传</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<link rel="stylesheet" type="text/css" href="js/uploadify/uploadify.css">
<script type="text/javascript" src="js/uploadify/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/uploadify/swfobject.js"></script>
<script type="text/javascript" src="js/uploadify/uploadify.js"></script>
<script type="text/javascript" src="js/uploadify/uploadify.min.js"></script>
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<script type="text/javascript">
$(function() {
$("#file_upload").uploadify({
debug:false,
auto:true,//是否自动上传
height: 30,
buttonText:'上传文件',
cancelImage:'js/uploadify/uploadify-cancel.png',
swf : 'js/uploadify/uploadify.swf',
expressInstall:'js/uploadify/expressInstall.swf',
uploader : '<%=path%>/upload/fileUpload.action', //后台处理上传文件的action
width : 120 ,
multi:false,//是否允许多个文件上传
queueID:'uploadfileQueue',
fileObjName:'fileName', //与后台Action中file属性一样
formData:{ //附带值
'userid':'111',
'username':'tom',
'rnd':'111'
},
successTimeout:99999,//上传超时时间
overrideEvents:['onDialogClose'],
fileTypeDesc:'上传文件支持的文件格式:jpg,jpge,gif,png',
fileTypeExts:'*.*',//*.jpg;*.jpge;*.gif;*.png
queueSizeLimit : 3,//
// simUploadLimit:1,//一次可以上传1个文件
fileSizeLimit:'20MB',//上传文件最大值
//返回一个错误,选择文件的时候触发
onSelectError:function(file, errorCode, errorMsg){
switch(errorCode) {
case -100:
alert("上传的文件数量已经超出系统限制的"+$('#file_upload').uploadify('settings','queueSizeLimit')+"个文件!");
break;
case -110:
alert("文件 ["+file.name+"] 大小超出系统限制的"+$('#file_upload').uploadify('settings','fileSizeLimit')+"大小!");
break;
case -120:
alert("文件 ["+file.name+"] 大小异常!");
break;
case -130:
alert("文件 ["+file.name+"] 类型不正确!");
break;
}
},
//每次更新上载的文件的进展
onUploadProgress: function(file, bytesUploaded, bytesTotal, totalBytesUploaded, totalBytesTotal) {
//alert(bytesUploaded);
//有时候上传进度什么想自己个性化控制,可以利用这个方法
//使用方法见官方说明
},
//检测FLASH失败调用
onFallback:function(){
alert("您未安装FLASH控件,无法上传图片!请安装FLASH控件后再试。");
},
//上传到服务器,服务器返回相应信息到data里
onUploadSuccess:function(file, data, response){
var fileNameAndPath=data.split(",");
var phtml="<p><a href='#' onlick=downLoad('"+fileNameAndPath[1]+"')>"+fileNameAndPath[0]+"</a><img alt='删除' src='js/uploadify/uploadify-cancel.png' onclick=delFile(this)></p>";
if($("#uploadfileQueue p").length==0){
$("#uploadfileQueue").html(phtml);
}else{
$("#uploadfileQueue p:last").after(phtml);
}
//alert(data+"上传成功");
},
onSelect : function(file) {
//alert(file.name);
},
removeCompleted:true,//上传的文件进度条是否消失
requeueErrors:false,
removeTimeout:2,//进度条消失的时间,默认为3
progressData:"percentage",//显示上传的百分比
onUploadError : function(file,errorCode,errorMsg,errorString,swfuploadifyQueue) {
$("#dialog-message").html(errorString);
} ,
onError:function(event, queueID, fileObj){
alert("文件:" + fileObj.name + " 上传失败");
}
});
});
//删除文件
function delFile(obj){
$(obj).parent().remove();
}
</script>
</head>
<body>
<input type="file" id="file_upload" name="fileName">
<div id="uploadfileQueue" style="width: 400px;">
</div>
</body>
</html>
5、 创建处理上传文件FileUploadAction.java,内容如下:
/**
* @title FileUploadAction.java
* @package com.ys.uploadfile.action
* @description 文件描述
* @author lijf
* @update 2012-12-13 下午04:17:35
* @version V1.0
*/
package com.ys.uploadfile.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
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.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import com.opensymphony.xwork2.ActionSupport;
public class FileUploadAction extends ActionSupport implements ServletRequestAware {
/**
* @fields serialVersionUID
*/
private static final long serialVersionUID = 1L;
private HttpServletRequest request;
private List<File> fileName;//这里的"fileName"一定要与表单中的文件域名相同
private List<String> fileNameContentType;//格式同上"fileName"+ContentType
private List<String> fileNameFileName;//格式同上"fileName"+FileName
private String savePath;//文件上传后保存的路径
/**
*
* @return
* @throws Exception
* @author lijf
* @description 上传文件
* @update 2013-1-26 下午02:15:26
*/
public void upload() throws Exception {//intentionPicture
String uploadFilename="";
File dir=new File(getSavePath());
String savePath=getSavePath();//保存上传文件的地址
if(!dir.exists()){
dir.mkdirs();
}
List<File> files=getFileName();
for(int i=0;i<files.size();i++){
FileOutputStream fos=new FileOutputStream(getSavePath()+"\\"+getFileNameFileName().get(i));
FileInputStream fis=new FileInputStream(getFileName().get(i));
byte []buffers=new byte[1024];
int len=0;
while((len=fis.read(buffers))!=-1){
fos.write(buffers,0,len);
}
fos.close();
fis.close();
uploadFileName=getFileNameFileName().get(i);
}
//设置响应内容的字符串编码
ServletActionContext.getResponse().setCharacterEncoding("UTF-8");
ServletActionContext.getResponse().setContentType("text/plain");
ServletActionContext.getResponse().getWriter().print(uploadFileName+","+savePath+"\\"+uploadFileName);
}
/* (non-Javadoc)下载文件
* @see com.opensymphony.xwork2.ActionSupport#execute()
*/
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return "success";
}
public InputStream getInputStream() {
return ServletActionContext.getServletContext().getResourceAsStream("/" + fileName);
}
/* (non-Javadoc)
* @see org.apache.struts2.interceptor.ServletRequestAware#setServletRequest(javax.servlet.http.HttpServletRequest)
*/
public void setServletRequest(HttpServletRequest req) {
this.request=req;
}
public List<File> getFileName() {
return fileName;
}
public void setFileName(List<File> fileName) {
this.fileName = fileName;
}
public List<String> getFileNameContentType() {
return fileNameContentType;
}
public void setFileNameContentType(List<String> fileNameContentType) {
this.fileNameContentType = fileNameContentType;
}
public List<String> getFileNameFileName() {
return fileNameFileName;
}
public void setFileNameFileName(List<String> fileNameFileName) {
this.fileNameFileName = fileNameFileName;
}
@SuppressWarnings("deprecation")
public String getSavePath() {
return request.getRealPath(savePath);
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
}
6、 struts2.xml配置内容如下
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 上传文件的action -->
<constant name="struts.multipart.maxSize" value="1024000000"/>
<package name="upload" namespace="/upload" extends="struts-default">
<action name="fileUpload" class="com.ys.uploadfile.action.FileUploadAction" method="upload">
<param name="savePath">/uploads</param>
</action>
</package>
</struts>
注:uploadify的属性配置请参考附件