为了账号安全,请及时绑定邮箱和手机立即绑定

我如何将图像从服务器发送到我的客户端?

我如何将图像从服务器发送到我的客户端?

冉冉说 2023-05-24 17:43:31
我一直在学习 spring 并将所有东西放在一起,我正在制作一个电子商务应用程序。我已经使用 rest api 连接客户端和服务器。现在我需要将图像发送给客户端。我的图像已经存储在 src/resources 文件夹中。我需要知道的是如何通过 rest api 发送这些图像。这样我就可以在我的客户中使用它我对此很菜鸟。我试过谷歌,我能找到的只是上传到服务器的图像文件的例子。我找不到通过 rest api 从服务器向客户端发送文件的示例。过去三天我一直被困在这这是我的休息控制器:现在我需要知道下一步该做什么,以便我可以发送图像@RestController@RequestMapping("/api")public class CategoriesRestController {// autowire customer service@Autowiredprivate CategoriesService service;//add mapping for GET all customer@GetMapping("/categories")public List<Categories> getCategories() {    return service.getCategories();}// adding mapping for GET only one customer@GetMapping("/categories/{categoryId}")public Categories getCategory(@PathVariable int categoryId) {    Categories categories = service.getCategory(categoryId);    if(categories == null) {        throw new CustomerNotFoundException("Customer id not found- "+ categoryId);    }else {    return categories;    }}// adding mapping for POST/customer i.e. insert a customer@PostMapping("/categories")public Categories addCategories(@RequestBody Categories theCategories) { //@RequestBody will convert JSON to JAVA object    // just to make things clear... always set id to 0 when inserting new object    // so that it will be created instead of update    theCategories.setId(0);    service.saveCategories(theCategories);    return theCategories;}
查看完整描述

2 回答

?
慕少森

TA贡献2019条经验 获得超9个赞

您可能以错误的方式思考问题。HTML 只需要图像的路径,而不是通过其余 API 发送图像本身。您将图像存储在一个目录中,您可以将图像的路径传递给您的 HTML。您可以向类别添加变量“imagePath”,HTML 可以在标签中引用它



查看完整回答
反对 回复 2023-05-24
?
一只名叫tom的猫

TA贡献1906条经验 获得超2个赞

您可以将图像转换为 base64:


byte[] fileContent = FileUtils.readFileToByteArray(new File(filePath));

String encodedString = Base64.getEncoder().encodeToString(fileContent);

然后通过您的 API 发送此属性。然后在你的客户端你可以像这样使用它:


<img src=json.encodedString />

这json是一个通过 API 发送的对象。


在发送之前,encodedString您可以在它的开头附加一些类似下面的内容,以便更容易在前端显示:


"data:image/png;base64,"

要在前端显示 base64 图像,您应该使用如下内容:


<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA

AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO

    9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />


查看完整回答
反对 回复 2023-05-24
  • 2 回答
  • 0 关注
  • 86 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信