转载自:https://blog.csdn.net/u010137431/article/details/46554767
背景
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如下
java
function change_photo(){
PreviewImage($("input[name='file_upload2']")[0], 'Img', 'Imgdiv');
}
其中PreviewImage方法是借用网上大神的代码,这里写链接内容
后台
首先要在Spring-servlet.xml中添加与文件上传相关的配置,这里的100000是图片大小(byte)
java
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="100000"/>
</bean>
Action部分
java
@Controller
public 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();
}
}
1
注意这里的ModeAndView需要Import的包是org.springframework.web.servlet.ModelAndView;否则返回前台很有可能是404错误;