Spring Boot提供了方便的方式来实现文件上传
和下载
功能。
1. 文件上传
创建一个Controller来处理文件上传请求:
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@RestController
public class FileUploadController {
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
try {
File convertedFile = new File("path/to/save/" + file.getOriginalFilename());
convertedFile.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(convertedFile);
fileOutputStream.write(file.getBytes());
fileOutputStream.close();
return "上传成功";
} catch (IOException e) {
return "上传失败";
}
}
}
2. 文件下载
创建一个Controller来处理文件下载请求:
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
@RestController
public class FileDownloadController {
@GetMapping("/download/{fileName:.+}")
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
Path filePath = Paths.get("path/to/save/" + fileName);
Resource resource;
try {
resource = new UrlResource(filePath.toUri());
} catch (IOException e) {
throw new RuntimeException("File not found: " + fileName);
}
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
}
}
- 在以上代码中,文件上传会将文件保存到指定路径,文件下载会根据文件名提供下载链接。