做了一个微信公众号的项目,需要上传用户的照片资料。使用了uploadifive.js插件做的图片上传。
具体操作如下:
参考文档:
1.引入相关js
<link rel="stylesheet" href="static/css/uploadifive.css">
<script type="text/javascript" src="static/js/jquery.uploadifive.js"></script>
2.input 标签
<span class="contM">照片</span>
<input type="file" id="f_zp" accept="image/*" />
<img class="img"/>
<input type="hidden" name="URL_ZP">
3.上传的js
$(function(){
$("input[id^='f_']").uploadifive({
//指定swf文件
'swf': '<%=basePath%>static/js/uploadify.swf',
//后台处理的页面
'uploadScript' : '<%=basePath%>uploadImg',
//按钮显示的文字
'buttonText': '上传图片',
//在浏览窗口底部的文件类型下拉菜单中显示的文本
'fileTypeDesc': 'Image Files',
//允许上传的文件后缀
'fileTypeExts': '*.gif; *.jpg; *.png',
//发送给后台的其他参数通过formData指定
'formData' : {
'timestamp' : '111'
},
//上传完成时的回调方法
'onUploadComplete' :function(file,data){
var temp=eval('(' + data + ')').content;
//因js控件会自动生成一下子标签。所以需要向上取父节点,才能得到想要的dom节点。
this[0].parentNode.parentNode.nextElementSibling.src=temp;
$(this[0].parentNode.parentNode).next().next().val(temp);
}
});
})
4.后台java相关代码
1.因为使用的是spring mvc进行的上传处理。所以需要在spring-mvc.xml中配置MultipartFile Bean .
<!-- 上传拦截,如最大上传值及最小上传值 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
<property name="maxUploadSize">
<value>104857600</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
<property name="defaultEncoding">
<value>utf-8</value>
</property>
</bean>
2.业务代码:
@RequestMapping(value = "/uploadImg")
@ResponseBody
public Result upload(@RequestParam(value = "Filedata", required = false) MultipartFile file, HttpServletRequest request, ModelMap model) {
Result result=null;
String path = request.getSession().getServletContext().getRealPath("uploadFiles");
String fileName = DateUtil.getCurrentTime()+RandomUtils.buildRandom(12)+StringUtils.substring(file.getOriginalFilename(), StringUtils.indexOf(file.getOriginalFilename(),"."));
File targetFile = new File(path, fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
try {
//保存
file.transferTo(targetFile);
result=new Result("成功");
result.setContent(request.getContextPath()+"/uploadFiles/"+fileName);
} catch (Exception e) {
result=new Result("失败");
e.printStackTrace();
}
//返回的数据格式为:
//{"header":{"status":1},"content":"/XXX/uploadFiles/20170609111534-415672534.png"}
return result;
}
参考文档:
jQuery上传插件Uploadify使用详解 http://fwhyy.com/2010/01/jquery-upload-plugin-uploadify-use-explanation/
jQuery无刷新上传之uploadify简单试用 http://www.cnblogs.com/babycool/archive/2012/08/04/2623137.html
官方文档 http://www.uploadify.com/documentation/