springboot如何实现文件上传和下载,给我编写一个简单的例子实现
时间: 2024-09-16 19:02:51 浏览: 72
Spring Boot实现文件上传和下载通常会用到MultipartFile接口和FileSystemResource类。这里是一个简单的例子来说明如何处理这两个操作:
1. **文件上传**:
首先,你需要在控制器方法上添加`@RequestParam("file") MultipartFile file`参数来接收上传的文件。然后,你可以将文件保存到服务器的某个位置。
```java
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
@RestController
public class FileUploadController {
@PostMapping("/upload")
public String handleFileUpload(@RequestParam("file") MultipartFile file) throws IOException {
if (file.isEmpty()) {
return "No file uploaded";
}
// 指定上传目录
String targetPath = "/path/to/upload/folder/" + file.getOriginalFilename();
File targetFile = new File(targetPath);
try {
file.transferTo(targetFile);
return "File uploaded successfully: " + targetFile.getAbsolutePath();
} catch (Exception e) {
throw new RuntimeException("Error uploading file", e);
}
}
}
```
2. **文件下载**:
对于文件下载,可以使用`ResponseEntity`返回一个`LinkedResource`,它从指定的文件系统路径读取内容。
```java
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.util.UriComponentsBuilder;
import java.io.File;
import java.net.URI;
@GetMapping("/download/{filename}")
public ResponseEntity<InputStreamResource> downloadFile(@PathVariable String filename) {
File file = new File("/path/to/download/folder/" + filename);
if (!file.exists()) {
return ResponseEntity.notFound().build();
}
InputStream inputStream = new FileInputStream(file);
HttpHeaders headers = new HttpHeaders();
headers.setContentDispositionFormData("attachment", filename);
return ResponseEntity.ok()
.headers(headers)
.body(new InputStreamResource(inputStream));
}
```
阅读全文