表单中有一种控件是可以将本地磁盘里的图片上传到应用服务器或网络地址上,点击这个控件可以浏览本地文件和选择本地文件。这里我们简单实现将文件上传到应用服务器某个目录下。
在上一节登录后的页面中,加入一个超链接,链接到upload.jsp。在upload.jsp中加一个form表单,表单中只有一个控件,类型为file。
/WebContent/jsp/index.jsp
/WebContent/upload.jsp
这里需要注意,action为"upload/"(最后有个/,防止Request method 'GET' not supported错误),enctype="multipart/form-data"必须加上,另外method="post"也必须有。只要是上传文件,就要用post方法,并且要注明enctype。
在PersonController.java中增加/upload方法,方法中的HttpServletRequest request对象改为了MultipartHttpServletRequest request,对上传的图片文件接收并保存到应用服务器的一个目录headPic中。在基础教程里已经实现了保存文件程序,这里需要从MultipartHttpServletRequest对象中取出fileName,并取出文件流InputStream,使用了request.getFileNames()。这段逻辑是上传文件操作普遍采用的方法,以后要上传文件就直接这样就可以拿到文件流进行处理。
@RequestMapping(value = "/upload", method = RequestMethod.POST) public Object upload(MultipartHttpServletRequest request, HttpServletResponse response) throws IOException { try { Iterator iterator = request.getFileNames(); MultipartFile mpf = null; while (iterator.hasNext()) { mpf = request.getFile(iterator.next()); if (mpf != null) { String fileName = mpf.getOriginalFilename(); InputStream ins = mpf.getInputStream(); File file = new File("E:\\apache-tomcat-6.0.9\\webapps\\calculateWeb\\headPic\\" + fileName); FileOutputStream os = new FileOutputStream(file); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); ins.close(); response.setContentType("text/html;charset=utf-8"); response.getWriter().print("上传成功 "); response.getWriter().print(""); } } } catch (Exception e) { e.printStackTrace(); } return null; }
重新启动Tomcat服务器,访问http://localhost/calculateWeb/loginForm.jsp进行登录,然后点击上传头像的链接进入上传页面。选择一个图片文件,点击上传头像按钮,就可以上传图片了。
但是这里会报一个Current request is not of type [org.springframework.web.multipart.MultipartHttpServletRequest]的错误,因为SpringMVC上传文件需要配置一个org.springframework.web.multipart.commons.CommonsMultipartResolver文件处理器。所以在applicationContext-mvc.xml配置文件中加入下面的配置,并且要加入两个jar包commons-fileupload-1.2.2.jar和commons-io-2.3.jar,放到WEB-INF/lib文件目录中即可。
http://central.maven.org/maven2/commons-fileupload/commons-fileupload/1.2.2/commons-fileupload-1.2.2.jar
http://central.maven.org/maven2/commons-io/commons-io/2.3/commons-io-2.3.jar
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
重启Tomcat再上传, 图片已经可以上传成功,并且打开tomcat的目录比如E:\apache-tomcat-6.0.9\webapps\calculateWeb\headPic,就可以找到文件已存在这个目录下面。
如果这里上传之后看不到图片显示出来,就在applicationContext-mvc.xml文件中加入一个配置因为SpringMVC拦截了所有/路径下的请求,比如这里图片地址为/headPic/*.jpg,SpringMVC也当成了请求PersonController的地址,当然没有这个方法请求路径,所以图片就没有处理。要让SpringMVC不拦截图片这种静态资源,就可以加入mvc:default-servlet-handler进行静态资源默认处理。
Java视频教程