SpringBoot+vue显示图片
前端:
后端请求路径:http://localhost/:8080/images
请求参数文件名:bw_platforms1700553054209.jpg
<img src="http://localhost:8080/images/bw_platforms1700553054209.jpg" alt="Image">
后端:
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
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.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
@RestController
@Validated
@RequiredArgsConstructor
@Slf4j
public class ImageController {
@Value("${file.path}") //从yml配置文件中获取 可以直接赋值给filePath字符串
private String filePath; //图片路径
@GetMapping("/images/{filename}")
public ResponseEntity<Resource> getImage(@PathVariable String filename) {
System.out.println(filename);
try {
// 构建图片文件路径
Path file = Paths.get(filePath).resolve(filename).normalize();
// 创建资源对象
Resource resource = new UrlResource(file.toUri());
// 检查资源是否存在并且可读
if (resource.exists() && resource.isReadable()) {
// 返回图片响应
return ResponseEntity.ok()
.contentType(MediaType.IMAGE_JPEG) // 根据实际图片类型设置MediaType
.body(resource);
} else {
return ResponseEntity.notFound().build();
}
} catch (MalformedURLException e) {
e.printStackTrace();
return ResponseEntity.notFound().build();
}
}
}