您的位置:宽带测速网 > 编程知识 > springboot文件上传功能怎么实现

springboot文件上传功能怎么实现

2025-06-13 13:50来源:互联网 [ ]

在Spring Boot中,实现文件上传功能通常需要使用Spring MVC的MultipartFile对象来接收并处理上传的文件。下面是一个简单的实现文件上传功能的示例代码:

    创建一个Controller类来处理文件上传请求:
@RestControllerpublic class FileUploadController {private final String UPLOAD_DIR = "uploads/";@PostMapping("/upload")public String handleFileUpload(@RequestParam("file") MultipartFile file) {try {Path filePath = Paths.get(UPLOAD_DIR + file.getOriginalFilename());Files.write(filePath, file.getBytes());return "File uploaded successfully!";} catch (IOException e) {return "Failed to upload file!";}}}
    在application.properties文件中配置文件上传的最大大小:
spring.servlet.multipart.max-file-size=10MBspring.servlet.multipart.max-request-size=10MB
    创建一个HTML表单来上传文件:
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>File Upload</title></head><body><form action="/upload" method="post" enctype="multipart/form-data"><input type="file" name="file"><button type="submit">Upload</button></form></body></html>

通过上述步骤,你就可以实现一个简单的文件上传功能。当用户在HTML表单中选择一个文件并点击上传按钮时,文件将被传输到指定的目录中,并返回上传成功或失败的消息。你可以根据实际需求对文件上传功能进行扩展和优化。