Spring MVC 文件上传

本文介绍了如何在SpringMVC应用中实现文件上传功能,包括添加相关依赖、配置MultipartResolver解析器以及编写Controller处理文件上传请求。示例代码展示了如何接收用户上传的文件并保存到服务器指定路径。
摘要由CSDN通过智能技术生成

文件上传

添加依赖

<!--文件上传-->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>

配置文件上传解析器

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

测试

  • 编写controller

    @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里面定义超链接

        <form action="/account/upload" method="post" enctype="multipart/form-data">
            文件: <input type="file" name="upload"></input>
            <input type="submit" value="提交">
        </form>
  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值