upload.js:
function ajaxFileUpload(type) {
$("#loading").ajaxStart(function() {
$(this).show();
}).ajaxComplete(function() {
$(this).hide();
});
$.ajaxFileUpload({
url : '${pageContext.request.contextPath}/upload?type=' + type, // 需要链接到服务器地址
secureuri : false,
fileElementId : 'file', // 文件选择框的id属性
dataType : 'json', // 服务器返回的格式,可以是json
success : function(data, status) // 相当于java中try语句块的用法
{
if (data.result) {
$('#result').html("上传成功");
} else {
$('#result').html("上传出错!请重新上传!");
}
},
error : function(data, status, e) // 相当于java中catch语句块的用法
{
$('#result').html("上传出错!请重新上传!");
}
});
return false;
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>
</head>
<body>
<form method="post" action="${pageContext.request.contextPath}/upload"
enctype="multipart/form-data">
<input type="file" id="file" name="file" />
<input type="button" value="提交" onclick="ajaxFileUpload(0)" />
<span> <img id="loading" alt="" src="images/loading.gif"
style="display: none;" /> </span>
</form>
<div id="result"></div>
<script type="text/javascript"
src="${pageContext.request.contextPath}/js/plugin/jquery.js">
</script>
<script type="text/javascript"
src="${pageContext.request.contextPath}/js/plugin/ajaxfileupload.js">
</script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/upload.js">
</script>
</body>
</html>
import java.io.File;
import javax.annotation.Resource;
import org.apache.struts2.json.annotations.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 上传文件
*
* @author gauze
*
*/
public class UploadAction{
/**
*
*/
private static final long serialVersionUID = -7438572057362014952L;
private static final Logger log = LoggerFactory
.getLogger(UploadAction.class);
@Resource
private UploadService uploadService;
private File file;
private String fileFileName = "";
private String fileContentType;
private boolean result;// 上传结果
private long size;
private Integer type;// 上传对象类型
private String saveUrl;// 文件保存url
public String execute() {
log.info("save file " + file);
saveUrl = uploadService.saveFile(type, file, fileFileName);// 保存文件
if (!saveUrl.isEmpty()) {
this.size = file.length();
this.result = true;
log.info("save file " + file + " successfully");
} else {
log.info("save file " + file + " failed");
}
return SUCCESS;
}
public void validate() {
result = false;
if (file == null || fileContentType == null || fileFileName == null
|| type == null) {
this.addActionError("upload failed!");
}
}
@JSON(serialize = false)
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;
}
@JSON(serialize = false)
public String getFileContentType() {
return fileContentType;
}
public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}
public void setResult(boolean result) {
this.result = result;
}
public boolean isResult() {
return result;
}
public void setSize(long size) {
this.size = size;
}
public long getSize() {
return size;
}
@JSON(serialize = false)
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public void setSaveUrl(String saveUrl) {
this.saveUrl = saveUrl;
}
public String getSaveUrl() {
return saveUrl;
}
}
Service(其中用到md5加密,md5加密代码就不提供了):
import java.io.File;
import java.io.IOException;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* 文件保存Service
*
* @author gauze
*
*/
public class UploadService {
private static final Logger log = LoggerFactory
.getLogger(UploadService.class);
/**
* 保存文件
*
* @param type
* 保存对象类型
* @param file
* 需要保存的临时文件
* @return 保存路径(url),异常返回空字符串
*/
public String saveFile(int type, File file, String fileName) {
log.debug("save file " + file);
String contextPath = "";
String newFileName = createUniqueName(fileName);// 生成新文件名
if (!newFileName.isEmpty()) {
// 根据类型选择存储位置
if (type == LOGO) {
contextPath = LOGO_PATH + "/" + newFileName;
} else if (type == DESIGN) {
contextPath = DESIGN_PATH + "/" + newFileName;
} else if (type == MEDIA) {
contextPath = MEDIA_PATH + "/" + newFileName;
} else {
log.error("invalid type and return empty string",
new Exception("无效的上传对象类型:" + type));
return "";
}
try {
FileUtils.copyFile(file, new File(ServletActionContext
.getServletContext().getRealPath(contextPath)));// 复制
} catch (IOException e) {
log.error("save failed and return empty string", e);
return "";
}
}
log.debug("save successfully and return " + contextPath);
return contextPath;
}
/**
* 根据文件名生成唯一新的文件名
*
* @param file
* 文件对象
* @return 新文件名,异常返回空字符串
*/
public String createUniqueName(String fileName) {
String name = "";
log.debug("createUniqueName for " + fileName);
try {
String suffix = fileName.substring(fileName.indexOf("."));// 文件后缀
String message = ServletActionContext.getRequest().getSession()
.getId()
+ fileName + new Date();
name = SecurityUtil.getSecurityCode(message, SecurityUtil.MD5)
+ suffix;
} catch (Exception e) {
log.error("createUniqueName failed and return empty string", e);
return "";
}
log.debug("createUniqueName successfully and return " + name);
return name;
}
// 上传对象类型
public static final Integer LOGO = 0;// logo
public static final Integer DESIGN = 1;// 创意设计
public static final Integer MEDIA = 2;// 影视
// 文件保存path
public static final String LOGO_PATH = "/source/images/logo";// logo path
public static final String DESIGN_PATH = "/source/images/design";// 创意设计path
public static final String MEDIA_PATH = "/source/media";// 影视path
}
struts配置:
<action name="upload" class="com.gzbugu.baisheng.action.member.UploadAction">
<result name="success" type="json">
<param name="contentType">text/html</param>
</result>
<result name="input" type="json">
<param name="contentType">text/html</param>
</result>
</action>
返回的json结果:{"fileFileName":"微博桌面截图_20121130223137.jpg","result":true,"saveUrl":"\/source\/images\/logo\/bb3be6711a30711faff47eee301504b9.jpg","size":15972}