SpringMVC 实现 文件上传功能

时间:2021-08-04 19:47:45

web.xml 不用特殊配置


spring-context.xml 需要加上一个 bean

    <!-- 配置MultipartResolver 用于文件上传 使用spring的CommosMultipartResolver -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="104857600" />
        <property name="maxInMemorySize" value="4096" />
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>

pom.xml 需要加上两个依赖

        <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.2</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>

controller 可以这样写

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public String queryBankCardDetail(@RequestParam("file") MultipartFile file) throws Exception {
        if (!file.isEmpty()) {
            try {
                // 文件存放服务端的位置
                String rootPath = "d:/tmp";
                File dir = new File(rootPath + File.separator + "tmpFiles");
                if (!dir.exists())
                    dir.mkdirs();
                // 写文件到服务器
                File serverFile = new File(dir.getAbsolutePath() + File.separator + file.getOriginalFilename());
                file.transferTo(serverFile);
                return "You successfully uploaded file=" + file.getOriginalFilename();
            } catch (Exception e) {
                return "You failed to upload " + file.getOriginalFilename() + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + file.getOriginalFilename() + " because the file was empty.";
        }
    }

上传文件这玩意坑神tm多,记录一下


参考资料:

1、Spring MVC 实现文件的上传和下载
https://blog.csdn.net/qian_ch/article/details/69258465

2、SpringMVC 文件上传配置,多文件上传,使用的MultipartFile
https://blog.csdn.net/swingpyzf/article/details/20230865

3、Spring MVC 上传文件(upload files)
https://blog.csdn.net/suifeng3051/article/details/51659731

4、Uploading Files
https://spring.io/guides/gs/uploading-files/