Khanh Pham
Khanh Pham

Reputation: 2973

upload file to s3 using nodejs

I have coded a function which upload file to s3 which using aws-sdk, but I've got a problem.

When I replace Body by Body: "test" then the function will execute successfully and I can see the content test in s3.

But I want to upload a document such as pdf file, it can't run and throws an error as:

UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be one of type string, Buffer, or URL. Received type object at Object.open (fs.js:406:3) at ReadStream.open (internal/fs/streams.js:110:12) at new ReadStream (internal/fs/streams.js:99:10) at Object.createReadStream (fs.js:1725:10)

This is my code:

import { createWriteStream, createReadStream } from "fs";
import AWS from 'aws-sdk';
const fs = require('fs');


const uploadS3 = async ({file}) => {
  const { stream, filename} = file;
  AWS.config.update({
    accessKeyId: '*******',
    secretAccessKey: '********',
    region: 'us-east-1' 
  });

  let params = {
    Bucket: "test-files-staging",
    Key: 'documents/' + filename,
    Body: fs.createReadStream(file),
    ACL: 'public-read'
  };
  await new AWS.S3().putObject(params).promise().then(() => {
    console.log('Success!!!')
  }).catch((err) => { console.log(`Error: ${err}`) })
}

Thanks in advance.

Upvotes: 3

Views: 4020

Answers (1)

Gibor
Gibor

Reputation: 1721

Well the error is pretty clear: the path argument needs to be string, buffer or URL, but you pass in an object which is the readStream created by fs.createReadStream.

Instead, use the fs.readFileSync function to read your file into a buffer (if you use the async fs.readFile you'll get a promise- which is again neither a string, buffer or URL and will fail again):

let params = {
    Bucket: "test-files-staging",
    Key: 'documents/' + filename,
    Body: fs.readFileSync(filename), // assuming filename is the full path to your object
    ACL: 'public-read'
  };

more info on fs functions can be found in documentation- here

Upvotes: 6

Related Questions