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>
相关推荐
春风解人意10 小时前
从零开始学习嵌入式P32----网络基础之TCP
c语言·网络·学习·tcp/ip
传奇开心果编程11 小时前
【Rust入门知识点学与练】第21课:Trait 进阶 Advanced Traits
开发语言·学习·rust
水巷石子11 小时前
备考系统架构设计师第一天
学习·架构·软考·设计·考试
是隼人12 小时前
buuctf-pwn inndy_echo(32位fmt)题解(学习过程持续更新)
c语言·学习·安全·pwn入门·ctf入门
m0_5873830012 小时前
全民健身解决方案软件开发实战:从架构设计到落地指南
java·spring boot·spring·架构·需求分析
wno70413 小时前
Spring Cloud Hystrix服务容错
spring·spring cloud·hystrix
xian_wwq13 小时前
【学习笔记】深度认知系列-第16讲-提示词工程
人工智能·笔记·学习
洛阳纸贵13 小时前
MATLAB-matlab基础知识
学习·算法·matlab
Vcaker13 小时前
Linux学习25-harbor私有仓库部署
linux·运维·学习
留白_14 小时前
【tableau入门学习】5、筛选器、参考线和集
学习·tableau