spring boot 如何实现将网络图片导出到浏览器端的固定目录下
时间: 2024-01-29 08:03:22 浏览: 33
Spring Boot 可以通过使用 `Resource` 类来实现将网络图片导出到浏览器端的固定目录下。具体步骤如下:
1. 在 `application.properties` 文件中配置文件上传的根目录:
```properties
upload.dir=/path/to/upload/dir
```
2. 创建一个 `FileUploadController` 类,用于处理文件上传的请求:
```java
@RestController
public class FileUploadController {
@Value("${upload.dir}")
private String uploadDir;
@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
File fileToSave = new File(uploadDir, file.getOriginalFilename());
file.transferTo(fileToSave);
return ResponseEntity.ok("File uploaded successfully!");
}
}
```
3. 创建一个 `FileDownloadController` 类,用于处理文件下载的请求:
```java
@RestController
public class FileDownloadController {
@Value("${upload.dir}")
private String uploadDir;
@GetMapping("/download/{fileName:.+}")
public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) throws MalformedURLException {
Path file = Paths.get(uploadDir).resolve(fileName);
Resource resource = new UrlResource(file.toUri());
if (resource.exists() || resource.isReadable()) {
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
} else {
throw new RuntimeException("Could not find the file!");
}
}
}
```
4. 在 HTML 页面中使用 `img` 标签来显示图片:
```html
<img src="/download/image.jpg" alt="Image">
```
当浏览器请求 `/download/image.jpg` 时,`FileDownloadController` 会将图片文件读取并发送给浏览器,使其在页面上显示出来。
以上是一个基本的实现方式,你可以根据你的具体需求进行调整和改进。