在Spring Boot中,可以使用MultipartFile类来处理文件上传。以下是一个简单的示例代码来展示如何在Spring Boot中进行文件上传:
创建一个控制器类来处理文件上传请求:import org.springframework.web.bind.annotation.*;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/upload")public class FileUploadController { @PostMapping("/singleFile") public String uploadFile(@RequestParam("file") MultipartFile file) { // 获取文件名 String fileName = file.getOriginalFilename(); // 保存文件到指定目录 // 这里可以根据自己的需求进行处理,比如保存到服务器的文件系统或者数据库中 // 这里只是简单示例,保存到本地磁盘 try { file.transferTo(new File("path_to_save_file/" + fileName)); return "File uploaded successfully: " + fileName; } catch (IOException e) { e.printStackTrace(); return "File upload failed: " + fileName; } }}配置文件上传的限制和临时存储位置(可选):在application.properties或application.yml中可以配置文件上传限制和临时存储位置,例如下面的配置:
# 设置文件上传的最大大小为10MBspring.servlet.multipart.max-file-size=10MB# 设置请求的最大大小为10MBspring.servlet.multipart.max-request-size=10MB# 设置文件上传的临时存储位置spring.servlet.multipart.location=/tmp创建一个前端页面来上传文件:<!DOCTYPE html><html><head> <title>File Upload</title></head><body> <h1>File Upload</h1> <form action="/upload/singleFile" method="post" enctype="multipart/form-data"> <input type="file" name="file"/> <br/><br/> <input type="submit" value="Upload"/> </form></body></html>通过以上步骤,您就可以在Spring Boot中实现文件上传功能了。当然,这只是一个简单的示例,您可以根据自己的需求来进一步完善和定制。


