We have a scenario where photo’s will be sent to a Cloud code task as a Byte array. How would I convert that to data that could be saved as an attachment (png)
here’s how I am grabbing an internet image and saving as an attachment.
Hope this helps.
// initial code by @tielman
// image was an object that came in via webhook.
let url = image.image_exchange_path;
let imageResponse = await fetch(url, {
method: "GET",
mode: 'no-cors',
browserFetch: true
})
let buffer = await imageResponse.arrayBuffer();
let mediaTypeFilename = getMediaTypeAndFileName(image);
// Create an Attachment in the JA attachment store
let attachment = await Attachment.create({
filename: mediaTypeFilename.filename,
mediaType: mediaTypeFilename.mediaType,
data: buffer
});
let parent_asset = await DB.asset.first("asset_tag = ?", image.asset_tag);
image.ps_asset_id = parent_asset.id;
await image.save();
And the function for filetype:
function getMediaTypeAndFileName(image) {
const mediaTypes = {
'.jfif': {mediaType: 'image/jpeg', extension: 'jpg'},
'.jpg': {mediaType: 'image/jpeg', extension: 'jpg'},
'.jpeg': {mediaType: 'image/jpeg', extension: 'jpg'},
'.png': {mediaType: 'image/png', extension: 'png'},
}
let specificMedia = mediaTypes[image.image_ext];
let filename = `${image.image_name}.${specificMedia.extension}`;
return {
mediaType: specificMedia.mediaType,
filename: filename
}
}
@bruce-hayes Can you please elaborate on the following.
- What do you mean by Byte array? [is it an ArrayBuffer, Buffer, Uint8Array, etc.] - can you share an example
- Where is the Byte array data coming from?
- How are you planning on sending it to CC? CC only accepts JSON payloads, and so you cannot send binary data directly to CC, but you can obviously work with it in the task itself since it’s running in a NodeJS environment
Unfortunately what exactly you mean by byte array isn’t clear, but I can offer the following.
To create an attachment in CC is very easy, you just need to use our Attachment API. To create an image Attachment you will need either a base64 or an ArrayBuffer representation of the data to pass into the Attachment.create()
method, like so …
let base64Data = `somebase64encodedData`;
let newAttachmentFromBase64 = await Attachment.create({base64: base64Data, filename: 'some_image.png'});
dbObject.attachment_field = newAttachmentFromBase64;
await dbObject.save()
let arrayBuffer = `someArrayBuffer`;
let newAttachmentFromArrayBuffer = await Attachment.create({data: arrayBuffer, filename: 'some_image.png'});
dbObject.attachment_field = newAttachmentFromArrayBuffer;
await dbObject.save()
If you are working with binary data, as opposed to a base64 string, then in most cases it should be relatively easy to convert your data to an ArrayBuffer (the exact mechanism will depend on exactly what kind of binary data you are working with, and in which environment you are doing the conversion
I hope this helps