使用iquery的插件ajaxFileUpload.js实现文件的异步上传。后台为java
1.在页面中引入jquery.js和ajaxFileUpload.js,切记jquery.js要在ajaxFileUpload.js之前。
2. html页面代码
3.javascript代码
function closeDiv(){
document.getElementById("edit_div").style.display="none";
}
function showDiv(){
document.getElementById("edit_div").style.display="block";
}
function commit(){
document.getElementById("edit_div").style.display="none";
$("#wait_loading").ajaxStart(function() {
$(this).show();
// 文件上传完成将div隐藏起来
}).ajaxComplete(function() {
$(this).hide();
});
//console.log("uploading");
if ($("#upload_file").val().length > 0) {
ajaxFileUpload();
}
else {
alert("请选择要上传的文件!!");
document.getElementById("edit_div").style.display="block";
}
}
function ajaxFileUpload(){
$.ajaxFileUpload({
url:"<%=basePath%>FileUploadServlet",
type: "post",
secureuri: false, //一般设置为false
fileElementId: 'upload_file', // 上传文件的id、name属性名
success: function(data, status){
alert("上传成功!");
location.reload();
},
error: function(data, status, e){
alert(e);
}
});
}
4.后台Servlet代码
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException,IOException {
String fileName = "";
//boolean isMultipart = ServletFileUpload.isMultipartContent(req);
DiskFileItemFactory factory = new DiskFileItemFactory();
// Configure a repository (to ensure a secure temp location is used)
ServletContext servletContext = req.getSession().getServletContext();
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);
System.out.println("-----------------uploading");
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");//解决中文乱码
try {
List items = upload.parseRequest(req);
for(FileItem item : items) {
//其他参数
String type = item.getContentType();
if(type == null) {
//System.out.println(item.getString(item.getFieldName()));
continue;
}
//文件参数
fileName = item.getName();
//设置保存文件路径
String realPath = this.getServletContext().getRealPath("/upload");
//System.out.println("-----------------realPath--"+realPath);
File dir = new File(realPath);
// System.out.println("-----------------filename--"+fileName);
if (!dir.exists() && !dir.isDirectory()) {
System.out.println(realPath+"目录不存在,需要创建");
//创建目录
dir.mkdir();
}
File f = new File(dir, fileName);
f.createNewFile();
//保存
item.write(f);
resp.getWriter().print("success");
}
}catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
本程序实现了点击按钮弹出选择上传文件的对话框,选定文件后,上传过程序中会有一个等待图片.gif 显示。
后出现问题,ajax里的data在带其他参数,后台接收不到,值为NULL,需修改ajaxfileUpload.js文件,可参考http://blog.csdn.net/u013243986/article/details/51497057