因为项目做提交的时候都用的ajax,需要加上上传图片功能,并且回显,就使用了Jquery的ajaxForm来提交。
后端使用SpringMVC自带的multipartFile
1.引入commons-fileupload.jar
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
2.在spring配置文件中声明使用multipartResolver解析上传的文件
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8" />
<!-- 上传文件大小限制 -->
<property name="maxUploadSize" value="10240000" />
</bean>
其他属性:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
2.在spring配置文件中声明使用multipartResolver解析上传的文件
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8" />
<!-- 上传文件大小限制 -->
<property name="maxUploadSize" value="10240000" />
</bean>
其他属性:
-defaultEncoding 编码方式
-maxInMemorySize 最大缓存
3.html
<div class="row"> <label class="col-sm-3 control-label"></label> <div class="col-sm-7"> <img src="" alt="" width="200px" id="showPic"> </div> </div> <input type="hidden" class="form-control" id="bannerUri"> <div class="row"> <label class="col-sm-3 control-label">上传图片</label> <div class="col-sm-7"> <form action="" enctype="multipart/form-data" method="post" id="uploadForm" > <input type="file" name="picFile"> <input type="submit" class="btn btn-primary" value="上传" id="upButton"/> </form> </div> </div>
4.js
引入
jquery.form.js
$('#upButton').on('click', function() { $('#uploadForm').on('submit', function() { $("#uploadForm").ajaxSubmit({ type: "POST", url:__path+"/banner/photoUpload", dataType: "json", success: function(data){ if(data.msg == 'SUCCESS'){ $("#showPic").attr("src", data.url); $("#bannerUri").val(data.url); } } }); return false; // 阻止表单自动提交事件 }); });
5.JAVA代码
/**
* 图片文件上传
*/
@ResponseBody
@RequestMapping(value = "/photoUpload",method = RequestMethod.POST)
public String photoUpload(MultipartFile picFile) throws IllegalStateException, IOException {
Map map = new HashMap();
if (picFile == null) return null;
Properties properties = null;
String path = null; // 文件路径
String type = null;// 文件类型
String fileName = picFile.getOriginalFilename();// 文件原名称
try{
properties = PropertiesUtil.getProperties("/props/appConfig.properties");
}catch (Exception ex){
ex.printStackTrace();
}
// 判断文件类型
type = fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()) : null;
if (type == null) return null;// 判断文件类型是否为空
if ("gif".equalsIgnoreCase(type) || "png".equalsIgnoreCase(type) || "JPG".equalsIgnoreCase(type)) {
// 项目在容器中实际发布运行的根路径
String realPath = PropertiesUtil.getPropVal(properties, "picPath"); //服务器中存放的文件路径
String urlPath = PropertiesUtil.getPropVal(properties, "picUrl"); //文件的url地址
// 自定义的文件名称 原名+随机数Md5+当前时间
Random random = new Random();
String trueFileName = MD5Util.makeMD5(fileName + random.nextInt(100)) + System.currentTimeMillis() + "." + type;
// 设置存放图片文件的路径
path = realPath + trueFileName;
System.out.println("存放图片文件的路径:" + path);
// 转存文件到指定的路径
picFile.transferTo(new File(path));
System.out.println("文件成功上传到指定目录下");
map.put("msg", "SUCCESS");
map.put("url", urlPath + trueFileName);
return JSONUtil.toJSONString(map);
} else {
System.out.println("不是我们想要的文件类型,请按要求重新上传");
}
return null;
}