SpringBoot学习笔记(十一:使用MongoDB存储文件 )
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.nio.file.Path;
import java.nio.file.Paths;
@RestController
public class FileUploadController {
private final StorageService storageService;
@Autowired
public FileUploadController(StorageService storageService) {
this.storageService = storageService;
}
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
storageService.store(file);
return ResponseEntity.ok("File upload successful: " + file.getOriginalFilename());
}
@GetMapping("/files/{filename:.+}")
public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {
Resource file = storageService.load(filename);
return ResponseEntity.ok().body(file);
}
}
这个代码实例提供了一个简单的文件上传和下载的REST API,使用Spring Boot和MongoDB存储文件。上传操作会将文件存储到MongoDB GridFS中,而下载操作则会从MongoDB中检索文件并返回给客户端。这个例子展示了如何使用Spring Data MongoDB存储和检索文件,并且如何通过Spring Boot创建REST API。
评论已关闭