Spring Boot 实现多图片上传并回显,涨姿势了~
@Controller
public class FileUploadController {
private final StorageService storageService;
@Autowired
public FileUploadController(StorageService storageService) {
this.storageService = storageService;
}
@GetMapping("/")
public String index() {
return "index";
}
@PostMapping("/upload")
public ResponseEntity<String> handleFileUpload(@RequestParam("files") MultipartFile[] files) {
List<String> fileNames = new ArrayList<>();
for (MultipartFile file : files) {
fileNames.add(storageService.store(file));
}
return ResponseEntity.ok(fileNames.toString());
}
@GetMapping("/download/{filename:.+}")
public ResponseEntity<Resource> downloadFile(@PathVariable String filename) {
Resource file = storageService.load(filename);
return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getFilename() + "\"")
.body(file);
}
}
在这个代码实例中,我们定义了一个FileUploadController
,它包含了文件上传和文件下载的逻辑。通过handleFileUpload
方法,用户可以上传多个文件,文件名称会被存储起来并以字符串形式返回。downloadFile
方法允许用户根据文件名下载文件。这里的StorageService
是一个抽象层,需要在实际的应用中实现。
评论已关闭