springboot如何通过url访问图片csdn
时间: 2023-05-08 17:58:52 浏览: 77
首先,需要在SpringBoot中创建一个Controller,用于处理URL请求。可以使用@RestController注解来声明该类为Controller类。在Controller类中,需要编写一个方法用于获取图片。该方法应使用@GetMapping注解来声明请求类型为GET,并将请求的URL链接作为参数传入方法。在方法中,可以使用Java IO流来获取图片。获取到图片后,需要设置Content-Type头信息,告诉浏览器返回的内容为图片信息。最后,将图片信息以字节流的形式返回给浏览器。
以下是代码示例:
@RestController
public class ImageController {
@GetMapping("/image")
public void getImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
String imageName = request.getParameter("imageName");
if (imageName != null) {
// 图片存放路径
String imagePath = "/path/to/images/" + imageName + ".jpg";
FileInputStream fis = new FileInputStream(imagePath);
byte[] bytes = new byte[fis.available()];
fis.read(bytes);
response.setContentType("image/jpeg");
OutputStream os = response.getOutputStream();
os.write(bytes);
os.flush();
os.close();
fis.close();
}
}
}
在浏览器中,可以通过以下格式来访问图片:
http://localhost:8080/image?imageName=image1
其中imageName就是图片的名称。需要将该名称作为参数传递给getImage方法。通过以上步骤,可以在SpringBoot项目中通过URL访问图片。