这里是一个简单的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,选择一个文件并单击“上传”按钮。如果一切正常,您应该会看到“文件已成功上传”的消息。检查应用程序的工作目录,您应该会发现上传的文件已经保存在那里了

写个springboot文件上传

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

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