Last Updated:
August 4, 2022
by
Kathy Ziomek
| Version: 24
| 1,007 views
| 1 follower
members are following updates on this item.
Using a provided code sample, developers can take a Base64 string and upload it as an image file to a folder channel. This also allows for data uploads that are quick and simple without having to go through the process of saving a file to your computer if you only have the file in Base64 format. The provided code example takes the Base64 data, converts it to a blob, and then converts it to a File object, which is then uploaded to a selected folder channel.
For more information about adding folder files, please see Add Folder Files.
Since there is no validation present in this code, this code is intended to be an example and is not intended to be deployed into a production environment.
To upload a file, you will need to know the GUID for the destination folder. To obtain the GUID, you will use one of the v1 Object endpoints.
API v1 (Get Object By Path):
Method: GET Path: /.api/api.svc/objects/byPath Parameters: path* (String), domain (String)
When formatting the endpoint, you will need to use the folder channel path as the parameter path.
The response to this request contains the parameter id, which is the GUID of the folder channel. This id value is important and will be used to upload the file. Here is a code snippet using JavaScript and Axios that can be used to obtain the id and store it in a variable:
let folderChannelPath = "/folderChannel"; let folderGuid; axios .get(`/.api/api.svc/objects/byPath?path=${folderChannelPath}`) .then(function (response) { folderGuid = response.data.response.id; });
Here is a JavaScript code sample that can be used to upload a file from a Base64 string:
/** * @name uploadBase64File * @description This method uploads a base64 image to Igloo */ let igFiles = { uploadBase64File: function (base64Image, folderGuid, fileName, title) { console.log("Working..."); /*this function takes the Base64 image and converts it into a blob for further processing*/ const b64toBlob = (b64Data, contentType = "", sliceSize = 512) => { const byteCharacters = atob(b64Data); const byteArrays = []; /*break the Base64 image up into smaller pieces and create an array of bytes to create the blob*/ for ( let offset = 0; offset < byteCharacters.length; offset += sliceSize ) { const slice = byteCharacters.slice(offset, offset + sliceSize); const byteNumbers = new Array(slice.length); for (let i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } const byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); } /*create the blob from the data*/ const blob = new Blob(byteArrays, { type: contentType }); return blob; }; /*identify the content type from the Base64 string*/ /*it's important to provide the entire Base64 string when uploading content using this function, since the complete string provides information about the content type which the function uses*/ let contentType = base64Image.split(";")[0].split(":")[1].trim(); console.log("Uploading: ", contentType); /*identify the image portion of the Base64 string*/ let content = base64Image.split(",")[1].trim(); /*using the function declared above, take the content and the contentType, and turn it into a blob*/ let blob = b64toBlob(content, contentType); /*using the blob, create a File object*/ /*at this step, the Base64 image is now in a File format, and we can proceed with the subsequent API calls normally*/ const imageFile = new File([blob], title, { type: contentType }); /*call the next function to upload the file, passing additional parameters through*/ this.uploadFile(imageFile, folderGuid, title, fileName); }, /** * @name uploadFile * @description This method creates a file upload object that will be used to facilitate the rest of the file upload process */ uploadFile: function (file, folderGuid, title, fileName) { /*declare additional variables that will be used when uploading the file*/ let fileId = null, chunkIdx = 0, chunkSize = null, newFileGuid = null; /*initiate the file upload by creating the file upload object using the information gleamed from the file in the previous function*/ new ApiClient({ apimethod: "file_upload/create", method: "post", postdata: { title: fileName, totalBytes: file.size, documentId: folderGuid, }, onSuccess: function (responseText, responseXML) { /*the file upload was created successfully*/ let result = JSON.parse(responseText); console.log(result); /*identify the id of the file upload*/ fileId = result.response.id; /*identify the chunk size necessary to upload the file*/ chunkSize = result.response.ChunkSize; /*start the Upload Chunk process by calling the next function*/ uploadChunks(chunkSize, title); }, }); /** * @name uploadChunks * @description This function handles chunking by our platform * @param {*} chunkSize */ function uploadChunks(chunkSize, title) { /*in order to upload the file, it will need to be broken down into smaller chunks*/ /*begin configuring the API call*/ let apiClient = new ApiClient({ sendimmediately: false, apimethod: "file_upload/" + fileId + "/add_chunk", apipath: "/.file_upload_api/", method: "post", urlEncoded: false, emulation: false, queryparams: { chunkIndex: chunkIdx, }, }); /** Get Request URL */ let requestUrl = apiClient.getRequestUrl(); /** Chunk handling logic */ let start = chunkIdx * chunkSize; let end = chunkSize; let total = start + end; if (total > file.size) { end = total - file.size; } let chunk = file.slice(start, total); /** Create the request */ let chunkRequest = new Request({ url: requestUrl, urlEncoded: false, noCache: true, headers: { "Cache-Control": "no-cache", "X-Requested-With": "XMLHttpRequest", "X-File-Name": encodeURIComponent(file.name), "X-File-Size": file.size, "X-File-Id": fileId, "X-File-Resume": "true", Accept: "application/json", }, onSuccess: function (responseText, responseXML) { var result = JSON.parse(responseText); console.log(result); /*Call the next function to update the file upload*/ updateDocument(title); }, onProgress: function (e) { var progress = parseInt(e.loaded) + parseInt(chunkIdx) * parseInt(chunkSize); progress = (progress / file.size) * 100; }, }); chunkRequest.sendBlob(chunk); } /** * @name updateDocument * @description This function updates the document with the file's information */ function updateDocument(title) { /*configure the API call to update the document*/ let apiClient = new ApiClient({ apimethod: "file_upload/" + fileId + "/update", method: "post", postdata: { title: title, /*this is where the file's title is decided*/ description: "", label: "", mimeType: file.contentType, parentId: folderGuid, }, onSuccess: function (responseText, responseXML) { var result = JSON.parse(responseText); console.log(result); /** Call function to publish the file */ createDocument(); }, }); } /** * @name createDocument * @description This function finally publishes the file to Igloo and completes the process. If this process completes successfully, then the file upload object from previous steps is deleted. */ function createDocument() { /*configure the API call to publish the file*/ let apiClient = new ApiClient({ apimethod: "file_upload/" + fileId + "/create_document", method: "post", queryparams: { mimeType: file.contentType, updateLastSignificantVersion: false, }, onSuccess: function (responseText, responseXML) { /** at this point, the file upload has completed successfully! */ var result = JSON.parse(responseText); console.log(result); }, }); } }, };
When this script is present in your application, you can upload a file using the following code snippet:
/** * @description Upload an image from Base64 to Igloo * @param {*} base64Image Base64 string of the image
* @param {*} folderGuid The GUID of the Igloo folder to upload the file into
* @param {*} fileName The intended file name of the image (e.g. image.png)
* @param {*} title The displayed title of the image (e.g. "A Tree")
*/ igFiles.uploadBase64File(
base64Image, folderGuid, fileName, title);
For the Postman documentation on the API endpoint that creates the file upload entry, please see Create a file upload entry.
For the Postman documentation on the API endpoint that uploads the document to the file upload entry, please see Upload document to upload entry.
For a JavaScript code example that uses the File API to upload a file, please see File API - How to upload a file.
For a more general explanation of the File Upload APIs, please see Uploading files into your digital workplace via API.
For a related code example that takes a Base64 string and converts it to be uploaded as a profile picture, please see Uploading Profile Photos from Base64.