Home > Blockchain >  amazon s3 - uploading empty image to bucket when using createWriteStream
amazon s3 - uploading empty image to bucket when using createWriteStream

Time:02-04

When using createWriteStream, without any error it uploads image to bucket but empty(size-0B).

const uploadImage = async (filePath, fileId) => {
  const fileStream = fs.createWriteStream(filePath);

  const uploadParams = {
    Bucket: bucket,
    ACL: "public-read",
    Body: fileStream,
    Key: filePath,
    ContentType: "image/png",
  };
  console.log(filePath);
  const data = await s3.upload(uploadParams).promise();
  console.log(data);
  return;
};

but when using readFileSync it uploads image correctly.

const uploadImage = async (filePath, fileId) => {
  const fileStream = fs.readFileSync(filePath);

  const uploadParams = {
    Bucket: bucket,
    ACL: "public-read",
    Body: fileStream,
    Key: filePath,
    ContentType: "image/png",
  };
  console.log(filePath);
  const data = await s3.upload(uploadParams).promise();
  console.log(data);
  return;
};

why?

CodePudding user response:

Problem that you have is more logical.

When you use createWriteStream you are creating new file on your file system. And basically you are creating empty file. So when you upload empty file on S3 it will be empty.

On the other hand when you use readFileSync you are reading the file from your file system, in your case picture, and send array of bytes to S3. That array of bytes is not empty but read from file system.

CodePudding user response:

The first solution must be a ReadStream to read file data from path. Use fs.createReadStream(filePath).

Flow: read file from path -> write to S3.

  • Related