Input表单写法:
<input type="file" multiple="multiple" accept="image/jpeg" name="newPhoto" value="" id="newPhoto">multiple选项用于声明是批量上传 accept声明只接收jpg格式的图片,其他格式的文件在选项卡中显示不出来
来自:http://www.cnblogs.com/kissdodog/archive/2012/12/15/2819025.html
一、ajaxFileUpload是一个异步上传文件的jQuery插件。
传一个不知道什么版本的上来,以后不用到处找了。
语法:$.ajaxFileUpload([options])
options参数说明:
1、url 上传处理程序地址。
2,fileElementId 需要上传的文件域的ID,即<input type="file">的ID。
3,secureuri 是否启用安全提交,默认为false。
4,dataType 服务器返回的数据类型。可以为xml,script,json,html。如果不填写,jQuery会自动判断。
5,success 提交成功后自动执行的处理函数,参数data就是服务器返回的数据。
6,error 提交失败自动执行的处理函数。
7,data 自定义参数。这个东西比较有用,当有数据是与上传的图片相关的时候,这个东西就要用到了。
8,type 当要提交自定义参数时,这个参数要设置成post
错误提示:
1,SyntaxError: missing ; before statement错误
如果出现这个错误就需要检查url路径是否可以访问
2,SyntaxError: Syntax error错误
如果出现这个错误就需要检查处理提交操作的服务器后台处理程序是否存在语法错误
3,SyntaxError: invalid property id错误
如果出现这个错误就需要检查文本域属性ID是否存在
4,SyntaxError: missing } in XML expression错误
如果出现这个错误就需要检查文件name是否一致或不存在
5,其它自定义错误
大家可使用变量$error直接打印的方法检查各参数是否正确,比起上面这些无效的错误提示还是方便很多。
使用方法:
引入jQuery与ajaxFileUpload插件。注意先后顺序,这个不用说了,所有的插件都是这样。
<script src="jquery-1.7.1.js" type="text/javascript"></script> <script src="ajaxfileupload.js" type="text/javascript"></script>
一个例子:
<html>
<head>
<script src="/jquery-1.7.1.js" type="text/javascript"></script>
<script src="/ajaxfileupload.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$(":button").click(function () {
if ($("#file1").val().length > 0) {
ajaxFileUpload();
}
else {
alert("请选择图片");
}
})
})
function ajaxFileUpload() {
$.ajaxFileUpload
(
{
url: '/Home/Upload',//用于文件上传的服务器端请求地址
secureuri: false,//一般设置为false
fileElementId: 'file1',//文件上传空间的id属性 <input type="file" id="file" name="file" />
dataType: 'HTML',//返回值类型 一般设置为json
success: function (data,status) //服务器成功响应处理函数
{
alert(data);
$("#img1").attr("src",data);
if (typeof (data.error) != 'undefined') {
if (data.error != '') {
alert(data.error);
} else {
alert(data.msg);
}
}
},error: function (data,status,e)//服务器响应失败处理函数
{
alert(e);
}
}
)
return false;
}
</script>
</head>
<body>
<p><input type="file" id="file1" name="file" /></p>
<input type="button" value="上传" />
<p><img id="img1" alt="上传成功啦" src="" /></p>
</body>
</html>
我的批量上传: ajaxFileUpload插件原理其实构建了一个表单form,里面很多file用于上传:最后submit()表单:见下面部分源码
var form = jQuery('<form action="" method="POST" name="'+ formId + '" id="' + formId
+ '" enctype="multipart/form-data"></form>');
if (data) {
for ( var i in data) {
jQuery('<input type="hidden" name="' + i + '" value="'
+ data[i] + '" />').appendTo(form);
}
}
提交函数:
function uploadHeadPhoto(){
var userId = $("#userId",navTab.getCurrentPanel()).val();;
if (userId == null) {
alertMsg.error("请选择用户ID"); //dwz框架
return;
}
//必须上传图片,才能注册
var newHeadPhoto = $("#newPhoto",navTab.getCurrentPanel()).val();
if (newHeadPhoto != null && newHeadPhoto != '') {
if (newHeadPhoto.toLowerCase().indexOf('.jpg') < 0) {
alertMsg.error("请上传JPG文件");
return;
};
} else {
alertMsg.error('请添加头像照片');
return;
}
var albumId = $("#albumId",navTab.getCurrentPanel()).val();
if (albumId == null || albumId=='') {
alertMsg.error("头像所属相册编号为空");
return;
}
//加载缓冲效果
//对应html页面的:<img id="loading" src="../images/loading.gif" style="display:none; width: 17px;">
$("#loading",navTab.getCurrentPanel()).ajaxStart(function() {
$(this).show();
}).ajaxComplete(function() {
$(this).hide();
});
$.ajaxFileUpload({
url : 'uploadMultiHeadPhoto.do',//服务器url
data : {
"albumId" : albumId,"userId" : userId
},secureuri : false,fileElementId : 'newPhoto',dataType : 'json',success : function(data,status) {
var photoList = eval("(" + data.message + ")");
var additionalRecord = '';
//将解析出来的图像上传后的url,上传状态做显示
for(var i=0 ;i<photoList.length;i++){
var record = "<img src='" + photoList[i].photoName + "' alt='" + photoList[i].id + "' id='headPhoto" + photoList[i].id +
"' onclick='selectHeadPhoto(this," + photoList[i].id +")' />";
additionalRecord += record;
}
//加载到该显示的地方
var headPhotoListTD=$("#headPhotoList",navTab.getCurrentPanel());
var orignalRecord = headPhotoListTD.html();
headPhotoListTD.html(orignalRecord + additionalRecord);
},error : function(data,e) {
alertMsg.info(e);
}
});
}
@RequestMapping(value = "uploadMultiHeadPhoto.do")
@ResponseBody
public AjaxResponseBean uploadMultiHeadPhoto(
@modelattribute("userInfoBean") UserInfoBean userBean,HttpServletRequest request,HttpServletResponse response,ModelMap map) {
UserInfoBean:
private List<multipartfile> newPhoto;
保存图片到本地并返回List<File>
public static List<File> saveFileList(List<multipartfile> multipartfiles,String parent,String extend) throws Exception {
List<File> files = new ArrayList<>();
if(parent == null){
// 保存文件的父目录
parent = makeParentDirectory();
}
if (multipartfiles == null || multipartfiles.size()<=0) {
return null;
}
for(multipartfile multipartfile : multipartfiles){
String originalFilename = multipartfile.getoriginalFilename();
if(StringUtil.isNotBlank(originalFilename)){
int index = originalFilename.lastIndexOf(".");
if(index > 0){
extend = originalFilename.substring(index);
}
}
// 生成一个随机数,保证同一时间 也不会生成相同的文件名
int temp = (int)Math.random() *1000;
String fileName = MD5.getMD5(originalFilename + temp + DateUtil.datetoString(new Date(),Format.YYYY_MM_DD_HH_MM_SS_SSS));
String savePath = parent +File.separator + fileName + extend;
File localFile = new File(savePath);
try {
multipartfile.transferTo(localFile);
files.add(localFile);
} catch (IllegalStateException e) {
throw e;
} catch (IOException e) {
throw e;
}
}
return files;
}
可以将List<File>再上传到图片服务器