![](/img/trans.png)
[英]How can I send from the server-side (Google App Engine, Cloud Endpoints) the information to my client?
[英]How can i send images from server to my client?
我一直在學習春天,為了使事情變得更緊密,我正在制作一個電子商務應用程序。 我已使用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;
}
您可能會以錯誤的方式思考問題。 HTML不需要通過其余的API發送圖像本身,而是僅需要圖像的路徑。 您將圖像存儲在目錄中,並且可以將圖像的路徑傳遞到HTML。 您可以將變量“ imagePath”添加到“類別”,HTML可以在標記中引用它
您可以將圖像轉換為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" />
閱讀更多:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.