首页 > 代码库 > springmvc图片上传(兼容ie8以上,实时预览)
springmvc图片上传(兼容ie8以上,实时预览)
html代码:
<form id="uploadform" method="post" enctype="multipart/form-data"> <table> <tr> <td><span class="need"> </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="http://www.mamicode.com/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="http://www.mamicode.com/‘ + evt.target.result + ‘" />‘; } reader.readAsDataURL(file.files[0]); } else { prevDiv.innerHTML = ‘<div class="img" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src=http://www.mamicode.com/‘‘ + 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>
springmvc图片上传(兼容ie8以上,实时预览)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。