1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > EasyUI上传图片 前台预览 后台读取

EasyUI上传图片 前台预览 后台读取

时间:2023-11-29 03:30:37

相关推荐

EasyUI上传图片 前台预览 后台读取

背景

Spring MVC + EasyUI

前台上传图片,并预览

下面是jsp的内容,form表单

java <form id="upload_form" enctype="multipart/form-data" action="upload_deal.do" method="post"><input class="easyui-filebox" style="width:300px" data-options='onChange:change_photo' id="file_upload" name="file_upload2"/><br/> <input type="submit" value="提交" /> <br/></form><div id="Imgdiv"><img id="Img" width="200px" height="200px"/></div>

对应调用JS如下

javafunction change_photo(){PreviewImage($("input[name='file_upload2']")[0], 'Img', 'Imgdiv');}

其中PreviewImage方法是借用网上大神的代码,这里写链接内容

后台

首先要在Spring-servlet.xml中添加与文件上传相关的配置,这里的100000是图片大小(byte)

java<bean id="multipartResolver" class="org.springframework.monsMultipartResolver"><property name="maxUploadSize" value="100000"/></bean>

Action部分

java@Controllerpublic class PictureTest {@Resource HibernateTemplate hibernateTemplate;@RequestMapping("/upload_deal")public ModelAndView upload_deal(@RequestParam(value="file_upload", required=false) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws IOException{savePicture(file, request);//保存图片List<Picture> pics = (List<Picture>)hibernateTemplate.find("from Picture");ModelAndView mav = new ModelAndView();mav.addObject("photo", pics.get(0).getPhoto_path());mav.setViewName("/Test/showPicture");return mav;}//文件保存到服务器上protected void savePicture(MultipartFile file, HttpServletRequest request)throws IOException, FileNotFoundException {String ImagePath = request.getSession().getServletContext().getRealPath("/static/img");File targetfile = new File(ImagePath, file.getOriginalFilename());Date date = new Date(System.currentTimeMillis());if(targetfile.exists()){String[] s = file.getOriginalFilename().split("\\.");s[0] += date.getTime();targetfile = new File(ImagePath, s[0] + "." + s[1]);}InputStream ins = file.getInputStream();FileOutputStream fos = new FileOutputStream(targetfile);byte b[] = new byte[1024];int temp = 0;while((temp = ins.read(b)) != -1){fos.write(b, 0, temp);}fos.close();ins.close();}}

注意这里的ModeAndView需要Import的包是org.springframework.web.servlet.ModelAndView;否则返回前台很有可能是404错误;

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。