一、下载uploadify3.2.1
二、在eclipse中新建struts2项目,并将uploadify导入webapp下
三、在pom.xml中引入依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.leech</groupId>
<artifactId>struts2-demo</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>struts2-demo Maven Webapp</name>
<!-- 属性配置 -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<junit.version>4.11</junit.version>
<struts2.version>2.3.20</struts2.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<!-- Struts2 依赖 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>${struts2.version}</version>
</dependency>
<!-- 加入jstl依赖包 -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2.1-b03</version>
<scope>provided</scope>
</dependency>
<!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.3</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.0.Final</version>
</dependency>
<!-- 加入slf4j依赖包 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
<!-- 这个包用于显示真实执行的sql -->
<dependency>
<groupId>com.googlecode.log4jdbc</groupId>
<artifactId>log4jdbc</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.47</version>
</dependency>
<!--
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.8</version>
</dependency>
-->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.8.3</version>
</dependency>
</dependencies>
<build>
<finalName>struts2-demo</finalName>
</build>
</project>
web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Struts Blank</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
struts.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>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="*_*" class="com.leech.action.{1}Action" method="{2}">
<result>/WEB-INF/{1}/{2}.jsp</result>
</action>
<action name="validatecode" class="com.leech.action.ValidateAction">
<result name="success" type="stream">
<param name="contentType">image/jpeg</param>
<param name="inputName">imageStream</param>
<param name="bufferSize">2048</param>
</result>
</action>
<action name="validatecodeverify" class="com.leech.action.ValidateAction" method="validatecodeverify"></action>
<action name="useradd" class="com.leech.action.UserAction" method="insert"></action>
<action name="index" class="com.leech.action.IndexAction">
<result>/login_03.jsp</result>
</action>
<action name="login" class="com.leech.action.LoginAction">
<result>/index.jsp</result>
</action>
<!-- 文件上传 -->
<action name="upload" class="com.leech.action.UploadAction" method="upload"></action>
</package>
</struts>
四、在webapp下新建uploadify_01.jsp如下
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" href="${ctx}/js/uploadify/uploadify.css">
<script type="text/javascript" src="${ctx}/js/jquery/jquery-1.7.2.js" ></script>
<script type="text/javascript" src="${ctx}/js/uploadify/jquery.uploadify.min.js" ></script>
<script type="text/javascript">
$(function() {
/**/
$("#file_upload").uploadify({
'auto' : false,
'buttonText' : " 浏 览... ", //上传按钮内容显示文本
//'buttonClass' : 'some-class',
'buttonCursor' : 'hand', //arrow
//'checkExisting' : '/uploadify/check-exists.php', //查检文件是否存在
//'debug' : true,
'fileObjName' : 'file', //与后台Action中file属性一样
'fileSizeLimit' : '4MB', //限制文件上传大小
'fileTypeDesc' : '支持格式:jpg,gif,png,bmp,jpeg',
'fileTypeExts' : '*.jpg;*.gif;*.jpeg;*.png;*.bmp',
//'formData' : {'userid' : '184562', 'userName' : '张三'}, 这里只能传静态参数
'height' : 25, //按钮高度
'method' : "post", //请求类型
'multi' : true,//是否为多文件上传
//'overrideEvents' : ['onDialogClose','onSelectError','onUploadError'], //需要重写的事件
'progressData':"percentage",//显示上传的百分比 //'progressData' : 'speed',
'queueID' : 'fileQueue', //队列ID,用来显示文件上传队列与进度
'queueSizeLimit' : 20, //队列一次最多允许的文件数,也就是一次最多进入上传队列的文件数
'removeTimeout' : 1,
'swf' : '${ctx}/js/uploadify/uploadify.swf', //上传动画,插件文件下的swf文件
//'successTimeout' : 50,//上传超时时间
'uploader' : '${ctx}/upload.action', //处理上传文件的服务类
//'uploadLimit' : 20, //上传文件个数限制
'width' : 70, //按钮宽度
'onInit' : function(instance) {
//console.info('The queue ID is ' + instance.settings.queueID);
},
'onFallback': function(){ //flash报错触发
alert("请您先安装flash控件");
},
'onUploadStart' : function(file) { //在onUploadStart事件中,也就是上传之前,把参数写好传递到后台。
var element={};
var v=encodeURIComponent(file.name);
element.realname=v;
element.userid='184562';
element.userName='张三';
$('#file_upload').uploadify('settings','formData',element);
},
'onUploadComplete' : function(file) {
//alert('The file ' + file.name + ' finished processing.');
},
'onUploadSuccess' : function(file, data, response) { 单个文件上传成功触发
//alert('The file ' + file.name + ' was successfully uploaded with a response of ' + response + ':' + data);
var json = $.parseJSON(data);
console.info(json.status);
},
'onUploadError' : function(file, errorCode, errorMsg, errorString) {
//alert('The file ' + file.name + ' could not be uploaded: ' + errorString);
}
});
/*
$("#file_upload").uploadify({
'debug' : false, //开启调试
'auto' : false, //是否自动上传
'swf' : '${ctx}/js/uploadify/uploadify.swf', //引入uploadify.swf
'uploader' : '${ctx}/upload.action',//请求路径
'queueID' : 'fileQueue',//队列id,用来展示上传进度的
'width' : '70', //按钮宽度
'height' : '25', //按钮高度
'queueSizeLimit' : 5, //同时上传文件的个数
'fileTypeDesc' : '视频文件', //可选择文件类型说明
'fileTypeExts' : '*.*', //控制可上传文件的扩展名
'multi' : true, //允许多文件上传
'buttonText' : '图片上传',//按钮上的文字
//'buttonImage':'jsp/networkdisk/images/btn_sc.gif',
'fileSizeLimit' : '20MB', //设置单个文件大小限制
'fileObjName' : 'file', //<input type="file"/>的name
'method' : 'post',
'removeCompleted' : true,//上传完成后自动删除队列
'onFallback':function(){
alert("您未安装FLASH控件,无法上传图片!请安装FLASH控件后再试。");
},
'onUploadStart' : function(file) {
var element={};
var v=encodeURIComponent(file.name);
element.realname=v;
$('#file_upload').uploadify('settings','formData',element);
},
'onUploadSuccess' : function(file, data, response){//单个文件上传成功触发
//data就是action中返回来的数据
// alert(file.name);
},
'onSelectError':function(file, errorCode, errorMsg){
var msgText = "选择文件有错误\n";
switch (errorCode) {
case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
//this.queueData.errorMsg = "每次最多上传 " + this.settings.queueSizeLimit + "个文件";
msgText += "每次最多上传 " + this.settings.queueSizeLimit + "个文件";
break;
case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
msgText += "文件大小超过限制( " + this.settings.fileSizeLimit + " )";
break;
case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
msgText += "文件大小为0";
break;
case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
msgText += "文件格式不正确,仅限 " + this.settings.fileTypeExts;
break;
default:
msgText += "错误代码:" + errorCode + "\n" + errorMsg;
}
alert(msgText);
},
'onQueueComplete' : function(){//所有文件上传完成
alert("文件上传成功!");
//location.href="/fusion/netWork/netWorkIndex!index.action";
}
});
*/
});
</script>
</head>
<body>
<h1>Uploadify Demo</h1>
<form>
<div id="fileQueue"></div>
<!-- <p>最多上传10张照片,尺寸480*800,格式jpg或png可批量上传</p> -->
<input id="file_upload" name="file_upload" type="file" multiple="true">
<input type="button" value="开始上传" onclick="javascript: $('#file_upload').uploadify('upload','*');" style="background: #505050;color:white;height:28px;margin-bottom: 0.5em;"/>
<input type="button" value="取消上传" onclick="javascript: $('#file_upload').uploadify('cancel','*');" style="background: #505050;color:white;height:28px;margin-bottom: 0.5em;"/>
</form>
</body>
</html>
五、UploadAction.java如下
package com.leech.action;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.struts2.ServletActionContext;
import com.alibaba.fastjson.JSON;
public class UploadAction {
private File file;// 上传的文件
private String fileFileName;// 上传的文件名
private String fileContentType;// 上传的文件类型
/**
* 上传文件
*
* @return
*/
public void upload() {
String userid = ServletActionContext.getRequest().getParameter("userid");
String userName = ServletActionContext.getRequest().getParameter("userName");
String realname = ServletActionContext.getRequest().getParameter("realname");
System.out.println("userid="+userid+";userName="+userName+";realname="+realname);
String realPath = ServletActionContext.getServletContext().getRealPath("/upload");
//String newFileName = FilenameUtils.getExtension(fileFileName);
StringBuffer newFileName = new StringBuffer();
newFileName.append(UUID.randomUUID().toString().replaceAll("-", ""))
.append(".").append(FilenameUtils.getExtension(fileFileName));
if (file != null) {
File saveFile = new File(new File(realPath), newFileName.toString());
if (!saveFile.getParentFile().exists()) {
saveFile.getParentFile().mkdirs();
}
try {
FileUtils.copyFile(file, saveFile);
Map<String, Object> map = new HashMap<String, Object>();
map.put("status", true);
map.put("url", "http://www.baidu.com");
ServletActionContext.getResponse().getWriter().write(JSON.toJSONString(map));
} catch (IOException e) {
e.printStackTrace();
}
}
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
public String getFileContentType() {
return fileContentType;
}
public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}
}
这里有两点需要注意 formData是客户端想要向服务器端传递的值,'formData':{ 'userid':'111', 'username':'tom', 'rnd':'111' } 和method一定要设置成get方式 'method' : 'get'
服务器端request.getParameter("userid“)就能取到值
还可以改写成如下方式
function uploadstart() {
$('#file_upload').uploadify('settings', 'formData', { 'folder':'task','pic':'groudpic'}); //设置表单数据
$('#file_upload').uploadify('upload','*'); //开始上传
}