Spring MVC学习之——上传文件

在Spring MVC中加入上传文件的功能

1.添加依赖

xml 复制代码
<!--文件上传-->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>

2.配置文件上传解析器

xml 复制代码
<!--配置文件上传解析器-->
<bean id="multipartResolver" 
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="5242880" />
    <property name="defaultEncoding" value="UTF-8" />
</bean>

3.测试

  • 编写controller

    注意在controller方法的参数中 MultipartFile upload的参数名一定要和jsp中上传input的name保持一致,否则会报空指针异常。

    java 复制代码
    @Controller
    @RequestMapping("/account")
    public class AccountController {
    
        @RequestMapping(path="/upload")
        public String upload(HttpServletRequest request, 
                                 MultipartFile upload,Model model) throws IOException {
            System.out.println("springmvc方式的文件上传");
            //获取要上传的文件目录
            String path = 
                request.getSession().getServletContext().getRealPath("/uploads");
            System.out.println("path:"+path);
            //根据文件上传的目录创建File对象,如果不存在则创建1个File对象
            File file = new File(path);
            if(!file.exists()){
                //创建一个file对象
                file.mkdirs();
            }
            //获取文件上传名称
            String filename = upload.getOriginalFilename();
            //完成文件上传
            upload.transferTo(new File(path,filename));
    
            model.addAttribute("msg", "欢迎你 springmvc");
            return "success";
        }
    }
  • 在index.jsp里面定义超链接

    注意表单在加入上传的input后,一定要写enctype="multipart/form-data",否则controller会接收不到,报错空指针

    html 复制代码
        <form action="/account/upload" method="post" enctype="multipart/form-data">
            文件: <input type="file" name="upload"></input>
            <input type="submit" value="提交">
        </form>
相关推荐
Flittly2 天前
【AgentScope Java新手村系列】(14)人机交互
java·spring boot·spring
唐青枫6 天前
Java Spring WebFlux 实战指南:用 Mono、Flux 和 WebClient 写响应式接口
java·spring
咖啡八杯7 天前
GoF设计模式——策略模式
java·后端·spring·设计模式
Flittly8 天前
【AgentScope Java新手村系列】(11)中断与恢复
java·spring boot·spring
dunky9 天前
Spring 的三级缓存与循环依赖
后端·spring
通信小呆呆13 天前
当算法有了“五感”:多模态数据融合如何向人体感官协同学习?
人工智能·学习·算法·机器学习·机器人
码云数智-园园13 天前
C++20 Modules 模块详解
java·开发语言·spring
H__Rick13 天前
自动对焦学习-3
人工智能·学习·计算机视觉
Daisy Lee13 天前
量化学习-第1章-什么是量化金融
学习·金融·datawhale
咖啡八杯13 天前
GoF设计模式——享元模式
java·spring·设计模式·享元模式