springboot写图片上传下载
时间: 2023-05-23 08:07:32 浏览: 54
A:Spring Boot可以很容易地实现图片上传和下载功能。下面是一个简单的示例代码,演示了如何处理图像上传和下载。
1. 图片上传功能
创建一个Spring Boot Controller类,处理图像上传请求:
```
@RestController
@RequestMapping("/api/image")
public class ImageController {
@PostMapping("/upload")
public String uploadImage(@RequestParam("file") MultipartFile file) {
try {
// 保存图片到本地磁盘或云存储
byte[] bytes = file.getBytes();
// ...保存图片代码...
return "上传成功!";
} catch (IOException e) {
e.printStackTrace();
return "上传失败!";
}
}
}
```
2. 图片下载功能
同样创建一个Spring Boot Controller类,处理图像下载请求:
```
@RestController
@RequestMapping("/api/image")
public class ImageController {
@GetMapping("/download")
public ResponseEntity<byte[]> downloadImage() {
try {
// 获取要下载的图片文件
String fileName = "test.jpg";
File file = new File(fileName);
// 将图片文件转换为字节数组
FileInputStream fis = new FileInputStream(file);
byte[] bytes = new byte[fis.available()];
fis.read(bytes);
fis.close();
// 设置HTTP响应头,表明响应类型为图片
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG);
headers.setContentDisposition(
ContentDisposition.builder("attachment")
.filename(fileName)
.build());
// 返回图片字节数组
return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
```
以上是基本的示例代码,您可以根据需求进行更改和优化。