<input type="file" name="file1" id="file1" onchange="uploadImg(‘file1‘,‘hidden1‘)">
<input type="hidden" id="hidden1" />
异步上传文件方法
function uploadImg(fileid,hiddenid) {
$.ajaxFileUpload
(
{
url: ‘/xxx/xxx‘,
secureuri: false,
fileElementId: fileid,
dataType: ‘json‘,
success: function (data, status)
{ //data的内容都是在后台php代码中自定义的,json格式返回后在这里以对象的方式的访问
if(typeof (data.errMsg) != ‘undefined‘){//上传文件出错
alert(data.errMsg);
}else{
alert(‘ok‘);
// $("#"+imgid).attr("src",data.path).addClass("load1");//加载返回的图片路径并附加上样式
$("#"+hiddenid).val(data.path); //给对应的隐藏域赋值,以便提交时给后台
}
},
error: function (data, status, e)
{
console.log(data);
}
}
)
}
@RequestMapping(/xxx/xxx)
@ResponseBody
public Map<String, Object> uploadFile(MultipartHttpServletRequest request) {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> names = request.getFileNames();
MultipartFile file = request.getFile(names.next());
....
// 保存文件
}
}