springmvc文件上传

一、导入相关依赖(还需要配置好springmvc的环境)

<!--文件上传-->
    <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.4</version>
    </dependency>

二、配置springmvc.xml

<!--配置文件解析器对象-->id是固定不变的
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--最大值限制为10M-->
        <property name="maxUploadSize" value="10485760"></property>
    </bean>

三、编写接收controller

利用srpingmvc封装的MultipartFile对象

@PostMapping(value = "/fileUpload")
    public void FileUpload(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        System.out.println("文件名 "+fileName);
        String path = request.getServletContext().getRealPath("");
        path = path + "upload/"+fileName;
        File filePath = new File(path);
        if (!filePath.exists()){
            filePath.mkdir();
        }
        System.out.println("保存路径 "+filePath);
     //直接执行保存操作 file.transferTo(filePath); }