【问题标题】:NodeJS: How would I compress a stream before uploading to S3?NodeJS:在上传到 S3 之前如何压缩流?
【发布时间】:2019-09-29 00:25:52
【问题描述】:

目前我正在将图像文件从我的移动应用程序上传到我的服务器,然后从我的服务器上传到 S3。像这样:

updateProgressPics: combineResolvers(
  isAuthenticated,
  async (parent, { pics }, { models, currentUser }) => {
    return pics.map(async (pic, i) => {
      const { file, filename, progressPicId } = pic;
      const { createReadStream } = await file;
      const stream = createReadStream();

      const { Location: url, Key: key, Bucket: bucket } = await S3.upload({
        stream,
        filename,
        folder: currentUser.id,
      });

      return await models.ProgressPic.findOneAndUpdate(
        { _id: progressPicId },
        { $set: { url, key, bucket } },
        { new: true, useFindAndModify: false }
      );
    });
  }

我的 S3 文件:

import AWS from "aws-sdk";
import fs from "fs";

import { AWS_CONFIG, S3_BUCKET } from "../../config";

AWS.config.update(AWS_CONFIG);

const s3 = new AWS.S3();

export const upload = async ({ folder, filename, stream }) => {
  const params = {
    Bucket: S3_BUCKET,
    Key: `${folder}/${filename}`,
    Body: stream,
  };

  const options = { partSize: 10 * 1024 * 1024, queueSize: 1 };

  return s3.upload(params, options).promise();
};

export default {
  upload,
};

我正在使用 Graphql 上传,它公开了 createReadStream 函数:https://github.com/jaydenseric/graphql-upload#readme

图像文件有点大 (3mb),我觉得即使使用 Cloudfront,它们也需要很长时间才能加载到设备上。我想在上传之前压缩它们以节省存储空间和性能原因。有没有办法专门针对流进行此操作?

【问题讨论】:

    标签: node.js amazon-s3 graphql


    【解决方案1】:

    我想在这种情况下,一个名为 sharp 的库将成为你的朋友。 我将在此处获得该库的链接,它广泛支持所有操作的流式传输。希望你能用这个解决你的压缩操作。

    关于你的性能因素,图书馆声称:

    由于使用了 libvips,调整图像大小通常比使用最快的 ImageMagick 和 GraphicsMagick 设置快 4 到 5 倍。

    【讨论】:

      猜你喜欢
      • 2019-02-10
      • 2020-10-11
      • 1970-01-01
      • 2021-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-12
      相关资源
      最近更新 更多