3

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.

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

3 Comments

i changed as your answer, but i got an error as: UnhandledPromiseRejectionWarning: Error: ENOENT: no such file or directory, open 'documet_1.pdf'
watch my comment, the filename has to be a full path to the file you're trying to load
@KhanhPham did it help you? if so please accpet the answer, or elaborate if you ran into another problem :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.