1,这是需要的三个jar包。
2,配置文件中需配置:
< bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver " > < property name="maxUploadSize" > < value >1000000000< / value > < / property > < / bean >3,表单form中:
需要代码:enctype="multipart/form-data"
且用type="file"表单
4,控制层接收
MultipartHttpServletRequest mreq = (MultipartHttpServletRequest)request; MultipartFile bfile = mreq.getFile("company.bus");
String name1 = bfile.getOriginalFilename(); //将图片保存 if(!name1.matches("\\w+\\.(jpg|png|gif)")){ throw new Exception("文件名不符合要求"); }
String path = request.getSession().getServletContext().getRealPath("upload"); //防止图片重名 int random1 = (int) (Math.random() * 10000);
String fileName1=System.currentTimeMillis()+random1+name1; File to1 = new File(path+"\"+fileName1);
try { //将上传的文件保存到指定目录 FileUtils.copyInputStreamToFile(bfile.getInputStream(), to1);
} catch (IOException e) { e.printStackTrace(); }
注意:
属性名字要写死 接收是也是用File,一般对象里是String来保存名字的,要加个File属性。