Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

S3 normal upload #8

Open
harryadel opened this issue Apr 8, 2021 · 1 comment
Open

S3 normal upload #8

harryadel opened this issue Apr 8, 2021 · 1 comment

Comments

@harryadel
Copy link

harryadel commented Apr 8, 2021

First, thank you for this awesome package, it saved us lots of effort implementing S3 in reaction-files.

Multipart upload is great for large uploads but not so much for small files so for anyone looking for how to implement normal upload it here's the code:

async _getWriteStream(fileKey, options = {}) {
    const opts = {
      Bucket: Meteor.settings.s3.bucket,
      Key: `${Date.now()}-${fileKey.filename}`
    };

    debug("S3Store _getWriteStream opts:", opts);
    debug("S3Store _getWriteStream options:", options);
    debug("S3Store _getWriteStream fileKey:", fileKey);
    debug("S3Store _getWriteStream objectACL", this.objectACL);

    let writeStream;

    let totalFileSize = 0;
    let chunks = [];
    writeStream = new Writable({
      write: async (chunk, encoding, callback) => {
        totalFileSize += chunk.length;
        chunks.push(chunk);

        callback();
      }
    });

    writeStream.on("finish", async () => {

      debug("S3Store writeStream finish");
      let uploadedFile = await this.s3.upload({
        ...opts,
        Body: Buffer.concat(chunks),
      }).promise();

      debug("S3 multipart upload completed", uploadedFile);
      // Emit end and return the fileKey, size, and updated date
      writeStream.emit("stored", {
        // Set the generated _id so that we know it for future reads and writes.
        // We store the _id as a string and only convert to ObjectID right before
        // reading, writing, or deleting.
        fileKey: uploadedFile.Key,
        storedAt: new Date(),
        size: totalFileSize
      });
    });

    return writeStream;
  }
@ghost
Copy link

ghost commented Apr 9, 2021

Thanks @harryadel that'll def come in handy in the future! Mind highlighting your code for us with a by adding js after the first three backticks?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant