jakirby
By:
jakirby

Can I upload images to Spaces using node.js

November 10, 2017 145 views
Node.js Ubuntu 16.04

I am wanting to use spaces to store image and log files from my nodej.js application. Is there a way to do this? I can only find stuff on how to upload using the console and nothing on how to do it with node.js

1 Answer
asb MOD November 10, 2017
Accepted Answer

Spaces is inter-operable with the AWS S3 API allowing you to take advantage of the existing ecosystem of tools for it. Below is a basic example demonstrating how to upload a file using the AWS JavaScript SDK, you can install it with:

npm install aws-sdk

The key is to set the endpoint to point to Spaces:

const AWS = require('aws-sdk')

// Configure client for use with Spaces
const spacesEndpoint = new AWS.Endpoint('nyc3.digitaloceanspaces.com');
const s3 = new AWS.S3({
    endpoint: spacesEndpoint,
    accessKeyId: 'ACCESS_KEY',
    secretAccessKey: 'SECRET_KEY'
});

// Add a file to a Space
var params = {
    Body: "The contents of the file",
    Bucket: "my-new-space-with-a-unique-name",
    Key: "file.ext",
};

s3.putObject(params, function(err, data) {
    if (err) console.log(err, err.stack);
    else     console.log(data);
});
Have another answer? Share your knowledge.