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

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

×
3 answers

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);
});
  • Hello, and thanks for this message.

    I followed what you have here and I successfully added a txt file. How could I rework this to upload an image received from the frontend? I posted a question on this topic, but in that thread I was attempting to solve the code differently than you have here.

    https://www.digitalocean.com/community/questions/image-upload-from-vue-express-to-spaces

  • Is this secure to store the secret key in react native codes? Some one can decode our app and steal this key.
    Can any one suggest a good method to resolve this issue?

    • Hi! You have to use your own server for uploading into Space in this case, and your React client has to simply send data to your server.

  • For anyone looking for a way to upload the file with PUBLIC permissions - just add ACL: ‘public-read’ to params

    var params = {
        Body: "The contents of the file",
        Bucket: "my-new-space-with-a-unique-name",
        Key: "file.ext",
        ACL: 'public-read'
    };
    
  • I followed the exact same steps but I am not able to understand the data type Blob it accepts.

    I am trying to upload image and I get this kind of data object from the frontend.

    { filename: '204764.jpg',
      mimetype: 'image/jpeg',
      encoding: '7bit',
      createReadStream: [Function: createReadStream] }
    

    I even tried converting it into a blob using new Blob() in the backend, but that didn’t work either.

we have uploaded the file,
but is it secured here,
as we there is no “acl” applied here.

putObject function give Etag only as a response nothing other than that?

Submit an Answer