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

我一直在学习 spring 并将所有东西放在一起,我正在制作一个电子商务应用程序。我已经使用 rest api 连接客户端和服务器。现在我需要将图像发送给客户端。我的图像已经存储在 src/resources 文件夹中。我需要知道的是如何通过 rest api 发送这些图像。这样我就可以在我的客户中使用它


我对此很菜鸟。我试过谷歌,我能找到的只是上传到服务器的图像文件的例子。我找不到通过 rest api 从服务器向客户端发送文件的示例。过去三天我一直被困在这


这是我的休息控制器:现在我需要知道下一步该做什么,以便我可以发送图像


@RestController

@RequestMapping("/api")

public class CategoriesRestController {


// autowire customer service

@Autowired

private 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;

}


冉冉说
浏览 89回答 2
2回答

慕少森

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

一只名叫tom的猫

您可以将图像转换为 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, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO&nbsp; &nbsp; 9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java