SpringBoot (二):文件上传

本文详细介绍了如何在SpringBoot项目中实现单文件和批量文件上传功能。通过配置MultipartConfigElement来设置文件大小限制,使用MultipartFile处理上传的文件,并在Controller中实现上传逻辑。同时提供了HTML表单用于文件选择和上传。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

新建一个SpringBoot项目:SpringBoot--uploadfile
工程目录:


11636334-a4d46587a89ccfd6
image

pom.xml依赖:

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
         <!-- thmleaf模板依赖. -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

FileUploadConfiguration文件信息配置:

public class FileUploadConfiguration {
    
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        // 设置文件大小限制 ,超出设置页面会抛出异常信息,
        // 这样在文件上传的地方就需要进行异常信息的处理了;
        factory.setMaxFileSize("256KB"); // KB,MB
        /// 设置总上传数据总大小
        factory.setMaxRequestSize("512KB");
        // Sets the directory location where files will be stored.
        // factory.setLocation("路径地址");
        return factory.createMultipartConfig();
    }

}

Controller类:

@Controller
public class FileUploadController {
    
    
     @RequestMapping(value = "/upload", method = RequestMethod.GET)
     public String upload() {
         return "/fileupload";
     }
     
     @RequestMapping(value = "/upload/batch", method = RequestMethod.GET)
     public String batchUpload() {
         return "/mutifileupload";
     }
        
        @RequestMapping(value = "/upload", method = RequestMethod.POST)
        @ResponseBody
        public String upload(@RequestParam("file") MultipartFile file) {
            if (!file.isEmpty()) {
                try {
                    // 这里只是简单例子,文件直接输出到项目路径下。
                    // 实际项目中,文件需要输出到指定位置,需要在增加代码处理。
                    // 还有关于文件格式限制、文件大小限制,详见:中配置。
                    BufferedOutputStream out = new BufferedOutputStream(
                            new FileOutputStream(new File(file.getOriginalFilename())));
                    out.write(file.getBytes());
                    out.flush();
                    out.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    return "上传失败," + e.getMessage();
                } catch (IOException e) {
                    e.printStackTrace();
                    return "上传失败," + e.getMessage();
                }
                return "上传成功";
            } else {
                return "上传失败,因为文件是空的.";
            }
        }

        /**
         * 多文件上传 主要是使用了MultipartHttpServletRequest和MultipartFile
         *
         */
        @RequestMapping(value = "/upload/batch", method = RequestMethod.POST)
        public @ResponseBody String batchUpload(HttpServletRequest request) {
            List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
            MultipartFile file = null;
            BufferedOutputStream stream = null;
            for (int i = 0; i < files.size(); ++i) {
                file = files.get(i);
                if (!file.isEmpty()) {
                    try {
                        byte[] bytes = file.getBytes();
                        stream = new BufferedOutputStream(new FileOutputStream(new File(file.getOriginalFilename())));
                        stream.write(bytes);
                        stream.close();
                    } catch (Exception e) {
                        stream = null;
                        return "You failed to upload " + i + " => " + e.getMessage();
                    }
                } else {
                    return "You failed to upload " + i + " because the file was empty.";
                }
            }
            return "upload successful";
        }
        
      

}

HTML文件配置:
单文件:

<title>文件上传示例</title>
</head>
<body>
    <h2>文件上传示例</h2>
    <hr/>
    <form method="POST" enctype="multipart/form-data" action="/upload">
        <p>
            文件:<input type="file" name="file" />
        </p>
        <p>
            <input type="submit" value="上传" />
        </p>
    </form>
</body>

批量文件:

<title>批量文件上传示例</title>
</head>
<body>
    <h2>批量文件上传示例</h2>
    <hr/>
    <form method="POST" enctype="multipart/form-data"
        action="/upload/batch">
        <p>
            文件1:<input type="file" name="file" />
        </p>
        <p>
            文件2:<input type="file" name="file" />
        </p>
        <p>
            文件3:<input type="file" name="file" />
        </p>
        <p>
            <input type="submit" value="上传" />
        </p>
    </form>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Radom7

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值