How to send a file from node to Amazon S3 using request?

165 views Asked by At

I'm trying to send a file using fs.createReadStream() but it doesn't work or give any errors.

I tried using request to put the file to s3 after steaming it from node.

const fs = require("fs");
const request = require("request");
const path = require("path");
let imagePath = path.join(__dirname,"../../public/images/img.jpg");

fs.createReadStream(imagePath).pipe(request.put(signedRequest));

when I change the first part to get an image from a url;

request.get('http://example.com/img.png').pipe(request.put(signedRequest));

it works and uploads the image to s3.

Is there a reason to why this is happening? Or is there any other method I can use to send a file from node to s3?

1

There are 1 answers

1
Grynets On

Try aws-sdk npm package.
Your code would look like this:

const params = {
  Bucket: bucket,
  Key: fileName,
  Body: data,
};

const options = {
  ACL: 'private',
  CacheControl: 'max-age=86400',
  ContentType: 'text/plain',
};

const s3 = new S3({
  region: 'us-east-1',
  apiVersion: '2006-03-01',
});

await s3.upload(params, options).promise();


Here is useful links: 1, 2