异步上传相信大家都做过类似的功能,JqueryAjaxFileUploader为我们提供了更简单的实现和使用方式。不过既然是JQUERY的插件那么它所依赖的环境大家都懂得。JqueryAjaxFileUploader并不华丽,也没有提供美化文件上传控件的css,它并不像jQuery File Upload(喜欢的同学可以去尝试下),提供了美观的样式和专门的图片预览、多任务上传等等, JqueryAjaxFileUploader 所拥有的很简单,只是异步上传文件的功能,当然这并不排除由你亲自为它披上一件华丽的外衣。
jQuery File Uplaod插件官方Demo:
好了言归正传,让我们一起来看下 JqueryAjaxFileUplaoder 的使用步骤:
<html>
<head>
<base href="<%=basePath%>">
<title>My starting page</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">
<script type="text/javascript" src="js/jquery.js">
</script>
<script type="text/javascript" src="js/ajaxfileupload.js">
</script>
<script type="text/javascript">
function ajaxFileUpload() {
$("#loading").ajaxStart(function() {
$(this).show();
})//开始上传文件时显示一个图片
.ajaxComplete(function() {
$(this).hide();
});//文件上传完成将图片隐藏起来
$.ajaxFileUpload( {
url : 'fileUpload.action',//用于文件上传的服务器端请求地址
secureuri : false,//一般设置为false
fileElementId : 'File',//文件上传控件的id属性
dataType : 'json',//返回值类型 一般设置为json
success : function(data, status) //服务器成功响应处理函数
{
alert(data.message);//从服务器返回的json中取出message中的数据,其中message为在struts2中定义的成员变量
if (typeof (data.error) != 'undefined') {
if (data.error != '') {
alert(data.error);
} else {
alert(data.message);
}
}
},
error : function(data, status, e)//服务器响应失败处理函数
{
alert(e);
}
})
return false;
}
</script>
</head>
<body>
<img src="img/loading.gif" id="loading" style="display: none;">
<input type="file" id="file" name="file" />
<br />
<input type="button" value="上传" οnclick="return ajaxFileUpload();">
</body>
</html>
注意:引入JS文件不要搞错了顺序,一定是先引入jQuery再引入插件。否则后果的严重性你是可以想到的。
上文中我请求了一个Action,并在Action里写好所需要的参数,以及文件格式的判断(这里我只是做的伪实现,过滤文件格式还请大家认真考虑),这个大家肯定都熟。
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class FileAction extends ActionSupport {
private File file;
private String fileFileName;
private String fileFileContentType;
private String message = "你已成功上传文件";
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
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 getFileFileContentType() {
return fileFileContentType;
}
public void setFileFileContentType(String fileFileContentType) {
this.fileFileContentType = fileFileContentType;
}
@SuppressWarnings("deprecation")
@Override
public String execute() throws Exception {
String path = ServletActionContext.getRequest().getRealPath("/upload");
try {
File f = this.getFile();
if(this.getFileFileName().endsWith(".exe")){
message="对不起,你上传的文件格式不允许!!!";
return ERROR;
}
FileInputStream inputStream = new FileInputStream(f);
FileOutputStream outputStream = new FileOutputStream(path + "/"+ this.getFileFileName());
byte[] buf = new byte[1024];
int length = 0;
while ((length = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, length);
}
inputStream.close();
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
message = "对不起,文件上传竟然失败了!!!!";
}
return SUCCESS;
}
}
还有重要的一步,配置Struts配置文件,一定要注意的是Action中result的配置contentType参数是一定要有的,否则浏览器总是提示将返回的JSON结果另存为文件,不会交给ajaxfileupload处理。这是因为struts2 JSON Plugin默认的contentType为application/json,而ajaxfileupload则要求为text/html。
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <package name="struts2" extends="json-default"> <action name="fileUpload" class="com.ajaxfile.action.FileAction"> <result type="json" name="success"> <param name="contentType"> text/html </param> </result> <result type="json" name="error"> <param name="contentType"> text/html </param> </result> </action> </package> </struts>Ok就是这样,要动手的同学马上Coding吧。顺便提供下JqueryAjaxFileUploader的JS文件。