这是一个简单的 Spring Boot 文件上传示例,使用了 Spring MVC 和 Apache Commons FileUpload 库:

  1. 首先,需要在 pom.xml 文件中添加以下依赖项:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>
  1. 创建一个文件上传控制器类:
@RestController
public class FileUploadController {

    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) {

        if (file.isEmpty()) {
            return "Please select a file to upload";
        }

        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(file.getOriginalFilename());
            Files.write(path, bytes);

            return "File uploaded successfully";
        } catch (IOException e) {
            e.printStackTrace();
            return "Failed to upload file";
        }
    }
}

在这个控制器中,我们使用 @PostMapping 注解来处理 POST 请求,接受名为 'file' 的文件参数。如果文件为空,我们返回一个错误消息。否则,我们使用 getBytes() 方法将文件转换为字节数组,使用 Paths.get() 方法创建一个路径对象,然后使用 Files.write() 方法将字节数组写入到文件中。

  1. 创建一个 HTML 表单页面:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>File Upload Example</title>
</head>
<body>
    <form method="post" enctype="multipart/form-data" action="/upload">
        <input type="file" name="file"/><br/><br/>
        <input type="submit" value="Upload"/>
    </form>
</body>
</html>

在这个表单页面中,我们使用 enctype="multipart/form-data" 属性来告诉浏览器这是一个文件上传表单。我们还指定了 action="/upload" 来将表单数据发送到我们之前创建的控制器中。

  1. 运行应用程序并测试文件上传功能。

可以使用以下命令在终端中启动应用程序:

mvn spring-boot:run

打开浏览器并访问 http://localhost:8080/upload-form.html,选择一个文件并单击 '上传' 按钮。如果一切正常,您应该会看到 '文件已成功上传' 的消息。检查应用程序的工作目录,您应该会发现上传的文件已经保存在那里了。

Spring Boot 文件上传示例:简单指南

原文地址: https://www.cveoy.top/t/topic/nsS1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录