springmvc图片上传(兼容ie8以上,实时预览)

时间:2022-03-14 19:24:09

html代码:

<form id="uploadform" method="post" enctype="multipart/form-data">
<table>
<tr>
<td><span class="need">&nbsp;&nbsp;&nbsp;</span>新闻图片:</td>
<td width="100" align="right"><input type="file"
onchange="preview(this)" name="newsImages" id="newsImages" /></td>
</tr>
<tr>
<td colspan="2">
<div id="preview"></div>
</td>
</tr>
</table>
</form>

js:

<script type="text/javascript" src="resource/js/jquery-1.9.1.min.js"></script>
<script src="http://malsup.github.io/jquery.form.js"></script>
function preview(file) {
var prevDiv = document.getElementById('preview');
if (file.files && file.files[0]) {
var reader = new FileReader();
reader.onload = function(evt) {
prevDiv.innerHTML = '<img src="' + evt.target.result + '" />';
}
reader.readAsDataURL(file.files[0]);
} else {
prevDiv.innerHTML = '<div class="img" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src=\'' + file.value + '\'"></div>';
}
uploadPhoto();
}
function uploadPhoto() {
var imagePath = $("#newsImages").val();
if (imagePath == "") {
alert("please upload image file");
return false;
}
var strExtension = imagePath.substr(imagePath.lastIndexOf('.') + 1);
if (strExtension != 'jpg' && strExtension != 'gif'
&& strExtension != 'png' && strExtension != 'bmp') {
alert("please upload file that is a image");
return false;
}
$("#uploadform").ajaxSubmit({
type : 'POST',
url : 'news/upload',
data : {
imgPath : $("#newsImages").val()
},
success : function(data) {
$("input[name='newsImage']").val(data);
},
error : function() {
alert("上传失败,请检查网络后重试");
}
}); }

controller:

@Controller
@RequestMapping(value = "/news")
public class NewsController { /**
* 处理上传的file文件的图片
* @author zhangyn
* @param map
* @param request
* @param newsImages
* @return
*/
@RequestMapping(value = "/upload")
@ResponseBody
public String upload(ModelMap map, HttpServletRequest request,
@RequestParam(value = "newsImages", required = false) MultipartFile newsImages) {
String pic_path = request.getSession().getServletContext().getRealPath("/")+"upload";//保存在项目下的upload文件夹下。
String fileName = newsImages.getOriginalFilename();
Date date=new Date();
long time = date.getTime();
File targetFile = new File(pic_path, time+fileName);//重命名的考虑是按照一定的格式存储利于查找,且避免了相同名称的覆盖。
if (!targetFile.exists()) {
targetFile.mkdirs();
}
try {
newsImages.transferTo(targetFile);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} return "upload/"+time+fileName;
}
}

spring-mvc.xml

    <!-- 上传文件拦截,设置最大上传文件大小 10M=10*1024*1024(B)=10485760 bytes -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10485760" />
</bean>