我一直在学习 Spring,为了将这些东西整合在一起,我正在制作一个电子商务应用程序。我使用rest api来连接客户端和服务器。现在我需要将图像发送给客户端。我的图像已经存储在 src/resources 文件夹中。我需要知道的是如何通过 REST API 发送这些图像。这样我就可以在我的客户端中使用它
我对此很菜鸟。我尝试了谷歌,我所能找到的只是图像文件上传到服务器的示例。我找不到通过 REST API 将文件从服务器发送到客户端的示例。过去三天我一直陷入这个困境
这是我的休息 Controller : 现在我需要知道下一步应该做什么,以便我可以发送图像
@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;
}
最佳答案
您可能以错误的方式思考问题。 HTML 不需要通过 REST API 发送图像本身,而是只需要图像的路径。您将图像存储在目录中,并且可以将图像的路径传递给 HTML。您可以将变量“imagePath”添加到类别,并且 HTML 可以在标记中引用它
关于java - 如何将图像从服务器发送到客户端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57439182/