繁体   English   中英

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

[英]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" />

阅读更多:

https://www.baeldung.com/java-base64-image-string

如何以HTML显示Base64图像?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM