springmvc上传文件

一个简单的springmvc文件上传例子

所需的依赖

只需要这个就好了。在idea的依赖关系图中,commons-fileupload包含了commons-io依赖

在这里插入图片描述

    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.2</version>
    </dependency>

一个简单的文件上传的页面

        <form action="http://localhost:8080/springmvc_Web_exploded/fff" method="post" enctype="multipart/form-data">
              <input type="file" name="file" id="filer_input" multiple="multiple">
              <input type="submit" value="Submit">
        </form>

在spring的配置文件中注入一个文件上传的bean

spring.xml

    <!--    文件上传的bean-->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--上传文件的最大大小,单位为字节 -->
        <property name="maxUploadSize" value="17367648787"></property>

        <!-- 上传文件的编码 -->
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>

实例代码

    @PostMapping("/fff")
    public String file(@PathVariable("file")MultipartFile file, HttpServletRequest req) throws IOException {

		//判断文件不存在
        if (file.isEmpty()){
            return "faile.html";
        }

        //我想放到这个地方文件的路径
        String realPath = req.getServletContext().getRealPath("/WEB-INF/file");
        //返回客户端文件系统中的原始文件名
        String filename = file.getOriginalFilename();
        File myFile = new File(realPath, filename);
        if (!myFile.getParentFile().exists()){
            myFile.getParentFile().mkdir();
            System.out.println("文件夹被创建了");
        }

		//将前端传过来的文件,传到自己new的File对象中
        file.transferTo(myFile);

        return "success.html";
    }
注意事项:
  1. 文件上传请求必须用post请求。
  2. 注意路径问题
  3. 前端的form表单必须添加 enctype="multipart/form-data"这个属性
  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值