node.js - NodeJS : How would I compress a stream before uploading to S3?

标签 node.js amazon-s3 graphql

目前,我正在将图像文件从我的移动应用上传到我的服务器,然后从我的服务器上传到 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,它们也需要很长时间才能加载到设备上。我想在上传之前对其进行压缩,以节省存储空间并出于性能原因。有没有办法专门针对流执行此操作?

最佳答案

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

关于您的性能因素,库声称:

Resizing an image is typically 4x-5x faster than using the quickest ImageMagick and GraphicsMagick settings due to its use of libvips.

关于node.js - NodeJS : How would I compress a stream before uploading to S3?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58148139/

相关文章:

javascript - 等待 SQL 查询完成 NodeJS SQLite 3

amazon-web-services - 在路径样式弃用后,存储桶名称中仍允许使用句点 (.)

javascript - 蒸发JS : Always get 403 SignatureDoesNotMatch error after resuming an upload

angular - *NgFor 不显示数据

node.js - 如何使用 Asana Node 客户端处理 OAuth access_token 过期?

javascript - sqlite.get() 导致 TypeError : Cannot read property 'get' of null

node.js - 是否可以使用 Morgan 记录错误消息?

python - appengine urllib 是否使用 SSLv3?传输安全协议(protocol)?

react-native - 如何在react-apollo graphql查询中正确使用动态变量?

java - 如何使用 HttpUrlConnect 通过 java 查询 Github graphql API