SpringMVC中的文件上传

1. springmvc对fileupload进行了封装,使用上传需要先导入fileupload的依赖:
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.2</version>
    </dependency>
2.还需要在springmvc的配置文件中配置文件解析器:
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10240000"/>

    </bean>

需要设置最大上传文件大小,并设置id

3.表单中需要指定提交方式为post,并将enctype改为multipart/form-data
4.完成以上设置,就可以在controller方法中接收文件了:
   
@Controller
public class UploadController {
    @RequestMapping("/upload")
    //文件类型 集合类型的 用注解声明一下  不然不会默认接收复杂类型
    public void upload(@RequestParam("head") CommonsMultipartFile head, HttpServletRequest request) throws IOException {
        //1.创建存储的文件名
        String filename = new Date().getTime() + ".jpg";//获得时间戳
        //2.获得存储文件的真实路径
        ServletContext servletContext = request.getServletContext();
        String realPath = servletContext.getRealPath("/img") + "/" + filename;
        //3.IO流的工具类 ,工具是fileUpload包的里的
        IOUtils.copy(head.getInputStream(),new FileOutputStream(realPath));
        //获取原始文件名
                //存数据库:/img+文件名
    }
}
注意该参数需要通过@RequestParam指定参数名

      

猜你喜欢

转载自blog.csdn.net/wangyucui123/article/details/80647104