LeoNature 2018-10-30
效果:
1. jar包导入:
<!-- 文件上传组件 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
2. 在spring的配置文件中加上:
<!-- 支持文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 请求编码格式 -->
<property name="defaultEncoding" value="utf-8"></property>
<!-- 上传文件大小(单位:字节) -->
<property name="maxUploadSize" value="50000000"></property>
<!-- 缓冲区大小(单位:KB) -->
<property name="maxInMemorySize" value="1024"></property>
</bean>
3. 从官网上下载可用的版本解压后添加到项目中,webapp下位置任意:
uploadify官方下载
4. jsp页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="/css/uploadify/uploadify.css" type="text/css">
</head>
<body >
<div class="container">
<h2>Basic Demo</h2>
<div id="fileQueue"></div>
<input type="file" name="file_upload" id="upload" />
<img id="img" style="width: 300px; height:250px;" src="images/uploadImgs/no_img.jpg" alt="image" />
</div>
<hr>
<script src="/js/jquery.min.js"></script>
<!-- uploadify -->
<script src="/css/uploadify/jquery.uploadify.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#upload").uploadify({
swf:"/css/uploadify/uploadify.swf",
uploader:"/system/updHeadImage",
fileObjName:"uploadFile", // 控制器中参数名称
auto:true,
fileSizeLimit:"1024KB",
fileTypeExts:"*.jpg;*.gif;*.png;",
onUploadSuccess:function(file, result, response) {
if(result){
// 设置图片路径
$("#img").attr("src",result);
}
// 上传失败
}
});
});
</script>
</body>
</html>
5.控制器:
/**
* 修改头像
* @return
* @throws Exception
*/
@ResponseBody
@RequestMapping(value="updHeadImage")
public String updHeadImage(MultipartFile uploadFile ,HttpServletRequest request) throws Exception {
_logger.info("+++++++++++++++++++++++ 执行修改头像 操作 +++++++++++++++++++++++ ");
File targetFile;
// 存储路径
String msgUrl = "";
// 是否上传成功标志
boolean flag = false;
// 取图片的原始名称、后缀
String fileName = uploadFile.getOriginalFilename();
if(fileName != null && fileName != ""){
// 存储路径
String returnUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() +"/images/uploadImgs/";
// 文件存储位置
String path = request.getSession().getServletContext().getRealPath("/images/uploadImgs/");
// 文件后缀
// String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());
// 新的文件名
// fileName = new Date().getTime()+"_"+new Random().nextInt(1000)+fileF;
String today = DateUtil.getDate(DateUtil.yyyy_M_d);
File fileToo =new File(path+"/"+today);
// 如果文件夹不存在则创建
if(!fileToo .exists() && !fileToo .isDirectory()){
fileToo .mkdir();
}
targetFile = new File(fileToo, fileName);
try {
uploadFile.transferTo(targetFile);
msgUrl = returnUrl+today+"/"+fileName;
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
}
if(flag){
return msgUrl;
}
return null;
}
6.修改英文为中文见:
修改jquery文件上传插件uploadify的英文为中文