ajaxupload.js 是一款使用jquery上传文件的js插件,对于简单的文件上传,足够可以应付。
该插件主要有以下几个选项:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | settings = { action: 'upload.php', //要提交的地址 name: 'userfile',//参数名次 data: {},//和文件一起提交的其它参数 autoSubmit: true,//选中文件后是否就提交 responseType: false,//返回的相应格式,如果是text格式的,会在响应前后加上一个<pre></pre>标签 hoverClass: 'hover', disabledClass: 'disabled', onChange: function(file, extension){//在选中了文件的时候触发 }, onSubmit: function(file, extension){//在提交的时候触发 }, onComplete: function(file, response){//上传结束的时候触发 } } |
你可以使用非自动提交的方式上传文件。
代码示例如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | var ajaxupload =new AjaxUpload($("#uploadFile_button"),{ action: "upload.action", type:"POST", data:{}, autoSubmit:false, responseType:"json", name:'file', onChange: function(file, ext){ if(ext && (/^(xls)$/.test(ext) )){ alert("只支持xls格式的文件"); } },
onComplete: function(file, resp){ alert("上传成功"); } }); |
以上代码绑定了id=uploadFile_button的html元素,只要点击它,就会弹出选择文件的对话框。
当选中了文件,你就可以手动触发它上传文件,当然你也可以在正式提交前设置一些参数。
1 2 | ajaxupload.setData({id,"1"}); ajaxupload.submit(); |
注意:当在chrome浏览器下面,该插件存在一个bug 就是重复选择相同的文件,onChange方法不会触发多次,
ajaxupload.js只适合简单的文件上传的场景,并没有显示速度的功能,也无法显示进度。
虽然该插件已经很久不再更新,但是使用简单,也有一些人一直在用。
如果你需要更强大的上传功能,ajaxupload.js可能不太适合你。
// Servlet
package com.my.servlet;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
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;
/**
* Servlet implementation class FileUploadServlet
*/
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public FileUploadServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out= response.getWriter();
//得到上传文件的路径
String savePath = this.getServletContext().getRealPath("/img");
DiskFileItemFactory dfif = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(dfif);
String newFileName="";
try {
List<FileItem> list =sfu.parseRequest(request);
for(FileItem file :list ){
if(file.isFormField()){
System.out.println(file.getFieldName()+" "+file.getString());
}else{
//得到上传文件的名称
String filename = file.getName();
//取得后缀
String ext =filename.substring(filename.lastIndexOf("."));
//System.out.println(ext);
newFileName = System.currentTimeMillis()+ext;
//得到保存的全名
savePath = savePath+File.separator+newFileName;
try {
file.write(new File(savePath));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.print("{'newfileName':'"+newFileName+"'}");
}
}
// JS
<%@ 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>
<script type="text/javascript" src="JS/jquery-3.1.0.min.js"></script>
<script type="text/javascript" src="JS/ajaxupload.3.6.js"></script>
<script type="text/javascript">
$(function(){
//alert(111);
var ajax = new AjaxUpload($("#uploadBtn"),{
action:"FileUploadServlet",
type:"POST",
data:{"myname":"mytest"},
autoSubmit:false,
responseType:"json",
/* name:'myfile', */
onChange: function(file, ext){
if(!(ext && /^(jpg|gif|bmp)$/.test(ext))){
alert("只支持jpg | bmp| gif");
return false;
}else{
ajax.submit();
}
},
onComplete: function(file, data){
// alert(response.test);
$("#show").html("<img src='img/"+data.newfileName+"' style='width:200px;height:200px;'/>");
}
});
});
</script>
</head>
<body>
<div id="show" ></div>
<button id="uploadBtn">上传</button>
</body>
</html>