springboot上传图片,下载图片
时间: 2023-11-07 14:59:23 浏览: 51
上传图片:
1.在Spring Boot中使用MultipartFile类来接收前端传递的文件。
2.在控制器中编写上传文件的方法,使用@RequestPart注解将前端传递的文件绑定到MultipartFile类型的参数上。
3.使用FileOutputStream将文件数据写入磁盘。
示例代码:
```
@PostMapping("/upload")
public String uploadImage(@RequestPart("file") MultipartFile file) {
// 获取文件名
String fileName = file.getOriginalFilename();
// 获取文件后缀名
String suffix = fileName.substring(fileName.lastIndexOf("."));
// 生成文件名
String newFileName = UUID.randomUUID().toString() + suffix;
// 上传文件路径
String filePath = "D:/images/" + newFileName;
// 写入磁盘
try (FileOutputStream fos = new FileOutputStream(filePath)) {
fos.write(file.getBytes());
} catch (IOException e) {
e.printStackTrace();
return "上传失败";
}
return "上传成功";
}
```
下载图片:
1.在控制器中编写下载文件的方法。
2.使用InputStreamResource将文件流包装成资源对象。
3.使用ResponseEntity将资源对象以文件流的形式返回给前端。
示例代码:
```
@GetMapping("/download")
public ResponseEntity<InputStreamResource> downloadImage() throws IOException {
// 文件路径
String filePath = "D:/images/xxxx.jpg";
// 获取文件流
File file = new File(filePath);
FileInputStream fis = new FileInputStream(file);
// 将文件流封装成资源对象
InputStreamResource isr = new InputStreamResource(fis);
// 构造响应头
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", "attachment; filename=" + file.getName());
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
// 返回响应实体
return ResponseEntity.ok()
.headers(headers)
.contentLength(file.length())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(isr);
}
```