Base64 Encoding Files
5 minute read
Overview
The Marketplacer Seller and Operator APIs can accept files for upload in a number of different scenarios, including but not limited to:
- Attaching images to products
- Uploading CSV files containing shipping zone post / zip codes
- Attaching packing slips to return shipments
Depending on the type of attachment, you can usually provide files in 1 of 2 ways:
- As a url accessible to the API
- As a Base64 encoded string
This walk-through covers option 2, detailing how you can base64 encode multiple files prior to upload via the API.
Disclaimer
Please refer to the license relating to the use of the code examples contained in this article.
Also note that as this code does not form part of the Marketplacer product, it is not covered by Marketplacer support.
Why use Base64 encoded files?
In some instances you do not have a choice in how you supply files to the Marketplacer API, (specifically those that use FileInput
), and only have the base64 option.
However, in instances where you do have the choice (typically when supplying images via ImageInput
), why would you choose base64 over supplying a URL?
The answer to this can vary, but for the most part it is usually related to the fact that the source-file urls cannot be publicly exposed to the Marketplacer APIs for retrieval, and you therefore need to find another vehicle to supply file data to the API. In this case base64 encoding prior to calling the API is an effective solution.
Solution Overview
The solution is a simple command line app that reads permitted file types from a local folder, and then writes out the Base64 encoded version to the console.
Further detail on the solution is provided below:
Component | Description |
---|---|
Language | C# & JavaScript |
Runtime | .NET / Node.Js |
Marketplacer API | Operator and Seller APIs |
Webhooks used | N/a |
Data Storage | File Storage |
Dependencies | No external dependencies in either language |
Choose Your Adventure
As we have provided examples in both C# & JavaScript, make sure to choose the correct option at each step when following this guide.Step 1 - Preparation
In this section we prepare our environment to ensure we have the correct run times set up as well as scaffold our projects.
Or you can click here to jump straight to the ๐ code below๐
Check .NET is installed
Check that you have the .NET SDK installed at version 8 or above:
dotnet --version
If not, you can download and install here.
Scaffold Project
dotnet new console -n Base64Generator_dotnet
Create folder & add files
Open project folder in VS Code (or alternative), create a files
folder and add some image and csv files:
Check Node.js is installed
Check that you have Node.js installed at version 20 or above:
node -v
If not, you can download and install here.
Create a project folder
We need to create a folder to contain our project, so issue a mkdir
command to create one:
mkdir Base64Generator_node
And then change into that directory:
cd Base64Generator_node
Scaffold Project
Making sure you’re “inside” the project directory, and initialize a new node project:
npm init
And answer the questions as you like, however for this app we’re changing the entrypoint to app.js
:
Create folder & add files
Open project folder in VS Code (or alternative) and:
- Create an
app.js
file - Create a
files
folder and add some image and csv files:
Step 2 - Code
Paste the following code into Program.cs
string folderPath = "./files";
string[] convertFiles = Directory.GetFiles(folderPath, "*.*", SearchOption.TopDirectoryOnly)
.Where(s => s.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase) ||
s.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase) ||
s.EndsWith(".png", StringComparison.OrdinalIgnoreCase) ||
s.EndsWith(".gif", StringComparison.OrdinalIgnoreCase) ||
s.EndsWith(".csv", StringComparison.OrdinalIgnoreCase))
.ToArray();
foreach (var file in convertFiles)
{
string base64String = ConvertFileToBase64(file);
Console.WriteLine("\n------------------------------");
Console.WriteLine($"File: {Path.GetFileName(file)}");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Base64 Encoded:");
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(base64String);
Console.ResetColor();
}
static string ConvertFileToBase64(string filePath)
{
byte[] fileBytes = File.ReadAllBytes(filePath);
return Convert.ToBase64String(fileBytes);
}
Paste the following code into app.js
const fs = require('fs');
const path = require('path');
const folderPath = './files';
function convertFileToBase64(filePath) {
const fileBuffer = fs.readFileSync(filePath);
return fileBuffer.toString('base64');
}
fs.readdir(folderPath, (err, files) => {
if(err) {
console.log('Error reading directory', err);
return;
}
const fileExtensions= ['.jpg', '.jpeg', '.png', '.gif', '.csv'];
files.forEach(file => {
const ext = path.extname(file).toLocaleLowerCase();
if(fileExtensions.includes(ext)) {
const fullPath = path.join(folderPath, file);
const base64String = convertFileToBase64(fullPath);
console.log('\n------------------------------');
console.log(`File: ${file}`);
console.log(`\x1b[32mBase64 Encoded:\x1b[0m`);
console.log(`\x1b[33m${base64String}\x1b[0m`);
}
});
});
Step 3 - Run
Run up the app:
dotnet run
You can now copy the yellow base64 encoded string(s) and use it with the Marketplacer APIs.
Run up the app:
node app
You can now copy the yellow base64 encoded string(s) and use it with the Marketplacer APIs.
Licensing
MIT License
Copyright (c) 2024 Marketplacer Pty Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.