Using Node.js to upload files to A2 Storage

Last updated: August 30, 2024

Login to the Web Portal with a valid American Cloud account

Go to Cloud Compute and select the VM to install Node.js on. If no VM is created yet Click Here.

Get the password and public IP for the cloud user of the VM to SSH into the VM

SSH into the VM ssh cloud@"PublicIP"

Install and configure Node.js

Run sudo apt-get update to ensure repositories are up to date

Install Node.js onto the VM using sudo apt install nodejs

Verify Node.js installed using node -v

Run sudo apt install npm to be able to install dependecies

Once Node.js is installed a dependency will need to be install npm install aws-sdk

Create a Node.js script to upload a file sudo nano upload-to-a2.js

const AWS = require('aws-sdk');
const fs = require('fs');

// Configure AWS SDK with your A2 endpoint and credentials
const s3 = new AWS.S3({
  endpoint: 'YOUR_A2_ENDPOINT', // Replace with your A2 endpoint. Don't include https://
  accessKeyId: 'YOUR_ACCESS_KEY',
  secretAccessKey: 'YOUR_SECRET_KEY',
  s3ForcePathStyle: true,
  region: 'a2-west', // This doesn't need to be specific it can be anything
});

// Define the bucket name and file name
const bucketName = 'your-bucket-name';
const fileName = 'file-to-upload.txt'; // Rename or code to automatically generate names for files
const tenant = 'YOUR_TENANT_ID' ;

// Read the file
const fileContent = fs.readFileSync(fileName);

// Construct the URL with endpoint preceding the bucket name
const fileURL = `https://${s3.config.endpoint}/${tenant}:${bucketName}/${fileName}`;

// Create parameters for A2 upload
const params = {
  Bucket: bucketName,
  Key: fileName, // The name you want to give to the file in A2
  Body: fileContent,
  ACL: 'public-read', // Set to different permissions if needed
};

// Upload file to A2 Storage
s3.upload(params, (err, data) => {
  if (err) {
    console.error('Error uploading file:', err);
  } else {
    console.log('File uploaded successfully. File URL:', fileURL);
  }
});

"YOUR_A2_ENDPOINT"

Copy the bucket URL the only thing needed will be the "region.americancloud.com" for the endpoint

"your-bucket-name"

"YOUR_TENANT_ID"

For testing create a file to test uploading touch file-to-upload.txt

Create Object Storage

  • To create and get the information needed from the A2 Storage Click Here.

Final Step

Once Node.js is installed and configured and the A2 storage is setup. This command can be used to run the script node upload-to-a2.js

Below is the successful output.