IC4J API Docs
  • Overview
    • Introduction
  • Quick Start
  • License
  • Reference
    • API Reference
      • Install IC4J Libraries
      • Supported Types
      • ReplicaTransport
      • Identity
      • Principal
      • AgentBuilder
      • ProxyBuilder
      • Using IDLArgs
      • QueryBuilder and UpdateBuilder
      • Using Raw Agent Methods
      • Handle Binary Payloads
      • Object Serializers and Deserializers
        • Pojo Serializer and Deserializer
        • JSON Jackson Serializer and Deserializer
        • JSON Gson Serializer and Deserializer
        • XML DOM Serializer and Deserializer
        • XML JAXB Serializer and Deserializer
        • JDBC Serializer
      • Android Development
Powered by GitBook
On this page
  1. Reference
  2. API Reference

Handle Binary Payloads

PreviousUsing Raw Agent MethodsNextObject Serializers and Deserializers

Last updated 1 year ago

The Internet Computer also allows developers to send and receive binary data like JPG or PNG images.

A fully functional example of how to use IC4J API to call a Canister method with binary payload can be found .

This is an example to use Motoko to call the canister.

The canister will receive a binary payload in add function and stores it. The Function get then returns the stored payload.

The Binary payload type is an array of Nat8.

main.mo
actor {
  let images = Map.HashMap<Text, Blob>(0, Text.equal, Text.hash);
  
  public func add(name : Text, image : [Nat8]) : async Text {
    let blob : Blob = Blob.fromArray(image);
    Debug.print("Source Image Size " #debug_show(blob.size()));
    images.put(name, blob );
    return  name;
  };

  public query func get(name : Text) : async [Nat8] {
    let blob : ?Blob = images.get(name);
    switch blob {
            case (null) { return [] };
            case (?image) { 
              Debug.print("Result Image Size " #debug_show(image.size()));
              Blob.toArray(image);
               };
        };  
  };
};
ImagesProxy.java
public interface ImagesProxy {	
	@QUERY
	@Name("get")
	public byte[] get(@Argument(Type.TEXT)String name );	
	
	@UPDATE
	@Name("add")
	@Waiter(timeout = 30)
	public CompletableFuture<String> add(@Argument(Type.TEXT)String name, @Argument(Type.NAT8)byte[] image);
}
Main.java
byte[] image = getImage(IMAGE_FILE, "png");
		
String name  = IMAGE_FILE;
ImagesProxy images = ProxyBuilder.create(agent, Principal.fromString(icCanister))
				.getProxy(ImagesProxy.class);		
CompletableFuture<String> proxyResponse = images.add(name, image);

String output = proxyResponse.get();		
byte[] imageResult = images.get(name);	

Binary Candid payload ([Nat8]) can be represented in Java either as byte[] array or Byte[] array.

In Java the is created with the 2 methods get and add.

Then in a simple Java class , can be used to create Canister Java proxy.

The source can be found in file.

here
canister code
proxy interface
ImageProxy
ProxyBuilder
Main.java