SpringMVC使用进阶-文件上传
来源:互联网 发布:java程序设计课后答案 编辑:程序博客网 时间:2024/06/05 07:31
如今文件上传的方式已经是遍地开花,各种五花八门的文件上传有的时候着实让人难以抉择,如果是使用springmvc也不用为文件上传而发愁,springmvc的文件上传比struts2的那个还要简单,就是寥寥无几的一点代码就能解决上传。
1 修改之前的配置文件
spring主要是编写配置文件比较麻烦,配置文件正确是程序正确执行的关键,同样的springmvc如果要支持文件上传也需要加上如下配置;
-
- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >
- <property name="defaultEncoding" value="gbk"/>
- <property name="maxInMemorySize" value="10240"/>
- <property name="uploadTempDir" value="/temp/"/>
- <property name="maxUploadSize" value="-1"/>
- </bean>
2 文件上传界面
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>文件上传</title>
- </head>
- <body>
- <form action="upload.do" method="post" enctype="multipart/form-data">
- 名称:<input type="text" name="name" /><br><br>
- 选择文件:<input type="file" name="image" /><br><br>
- <input type="submit" value="确认上传"/>
- </form>
- </body>
- </html>
无论jsp、php、asp.net上传文件一般都通过表单上传,而且还必须有enctype="multipart/form-data",否则文件将无法上传成功,还需要注意的一点就是springmvc的上传实现使用的是commons-io,因此相应的jar包也不能少。
3 文件上传控制器
- package org.hncst.controller;
-
- import java.io.File;
- import java.util.Date;
-
- import javax.servlet.ServletContext;
-
- import org.springframework.stereotype.Component;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.context.ServletContextAware;
- import org.springframework.web.multipart.commons.CommonsMultipartFile;
-
- @Controller
- public class FileUploadController implements ServletContextAware{
- private ServletContext servletContext;
- public ServletContext getServletContext() {
- return servletContext;
- }
-
- public void setServletContext(ServletContext servletContext) {
- this.servletContext = servletContext;
- }
- @RequestMapping(value="/upload.do", method = RequestMethod.POST)
- public String uploadFile(String name,@RequestParam("image") CommonsMultipartFile file) {
- String path=this.servletContext.getRealPath("/upload");
-
- String fileName=file.getOriginalFilename();
-
- String fileExt=fileName.substring(fileName.lastIndexOf("."));
-
- File file2=new File(path,new Date().getTime()+fileExt);
-
- try {
- file.getFileItem().write(file2);
- } catch (Exception e) {
-
- e.printStackTrace();
-
- return "redirect:uploadFailure.jsp";
- }
- return "redirect:uploadSuccess.jsp";
- }
-
-
- }
0 0