背景:我们平时在做项目的时候,肯定会遇到上传头像、图片、文件等异步上传的功能,今天就以ajaxFileupload组件上传头像为例总结一下该组件的用法。
Tips: 我在以前的博客中分享过三种上传组件,其实主要代码已经在这篇文章体现了,今天再次总结一下ajaxfileupload这个组件,发现在高版本(1.9以上)的Jquery下ajaxfileupload提示异常,然后我就把ajaxfileupload的jQuery对象都替换成了$就可使用了,对于ajaxFileUpload 报这错jQuery.handleError is not a function,请猛戳 这里,对就是这里。附件是修改好可使用的ajaxfileupload.js文件。
需求:自定义样式【上传】按钮,点击之后【上传】按钮,打开文件选择对话框,选择文件后自动上传,并可预览该图片。
分析:
1.【上传】按钮是a链接,但是上传文件必然需要一个input type="file"的元素,在点击a链接这个【上传】按钮的时候,触发input type="file"元素的click方法打开文件选择对话框,选择文件后,触发input type="file" 的onchange方法,然后调用ajaxfileupload的上传方法开始上传。
用到的技术:jquery,ajaxfileupload,springMVC
代码:
1.HTML片段
<div class="uploadPicture">
<img id="imgHead" src="" width="106" height="122" alt="头像">
<input type="file" onchange="uploadHead();" id="basicInfoHead" style="display:none;"
name="basicInfoHead" />
<input type="hidden" id="basicHeadUrl" >
<a href="#basicInfo" id="uploadBasicInfoHead" >上传头像</a>
</div>
2.JS代码
//上传头像,触发click方法 $('#uploadBasicInfoHead').on('click',function(){ $('#basicInfoHead').click(); }); function uploadHead(){ $.ajaxFileUpload({ url:"${pageContext.request.contextPath}/profile/uploadBasicHead",//需要链接到服务器地址 secureuri:false, fileElementId:"basicInfoHead",//文件选择框的id属性 dataType: 'json', //json success: function (data) { $("#imgHead").attr("src","${pageContext.request.contextPath}/profile/readImage?imagePath="+data.imagePath); $('#basicHeadUrl').val(data.imagePath); },error:function(XMLHttpRequest, textStatus, errorThrown){ alert('上传失败!'); } }); };
3.JAVA代码
//上传文件方法
@RequestMapping(value = "profile/uploadBasicHead", produces = "text/plain;charset=UTF-8")
@ResponseBody
public String ajaxUpload(HttpServletRequest request) throws IllegalStateException,
IOException {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
String fileName = "";
String uploadPath = "uploadFile/head/";
String path =request.getSession().getServletContext().getRealPath("/")+uploadPath;
/*File uploadPathFile = new File(path);
if (!uploadPathFile.exists()) {
uploadPathFile.mkdir();
}*/
String realPath = "";
for (Iterator it = multipartRequest.getFileNames(); it.hasNext();) {
String key = (String) it.next();
MultipartFile mulfile = multipartRequest.getFile(key);
fileName = mulfile.getOriginalFilename();
fileName = handlerFileName(fileName);
File file = new File(path + retFileName);
mulfile.transferTo(file);
}
realPath = "{\"imagePath\":\""+uploadPath+fileName+"\"}";
return realPath;
}
//文件名称处理
private String handlerFileName(String fileName) {
//处理名称start
fileName = (new Date()).getTime()+"_"+fileName;
//时间戳+文件名,防止覆盖重名文件
String pre = StringUtils.substringBeforeLast(fileName, ".");
String end = StringUtils.substringAfterLast(fileName, ".");
fileName = Digests.encodeByMd5(pre)+"."+end;//用MD5编码文件名,解析附件名称
//处理名称end
return fileName;
}
//预览,获取图片流
@RequestMapping(value = "profile/readImage", produces = "text/plain;charset=UTF-8")
public void readImage(HttpServletRequest request, HttpServletResponse response){
String imagePath = request.getSession().getServletContext().getRealPath("/")+request.getParameter("imagePath");
try{
File file = new File(imagePath);
if (file.exists()) {
DataOutputStream temps = new DataOutputStream(response
.getOutputStream());
DataInputStream in = new DataInputStream(
new FileInputStream(imagePath));
byte[] b = new byte[2048];
while ((in.read(b)) != -1) {
temps.write(b);
temps.flush();
}
in.close();
temps.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}