【问题标题】:Why S3 only stores the last item of my loop?为什么 S3 只存储我循环的最后一项?
【发布时间】:2015-08-14 20:01:44
【问题描述】:

我正在尝试使用节点 AWS 开发工具包上传图像,但在使用循环时遇到问题。

这是我的节点模块:

gm = require('gm').subClass imageMagick: true
s3 = require '../../modules/s3'
Photo = require '../../models/Photo'
sizes =
  t: 100
  m: 240
  z: 640
  l: 1024
  k: 2048
newPhoto = new Photo
newPhotoImg = gm process.cwd() + '/' + req.files.file.path
for key, val of sizes
  newPhotoImg
  .resize(null, val)
  .toBuffer 'jpg', (err, buffer) ->
    if err then console.error err and res.status(500).end() else
      params =
        Key: newPhoto.id + '-' + key + '.jpg'
        Body: buffer
        ContentType: 'image/jpeg'
      s3.putObject params, (err, data) ->
        if err then console.error err else console.log data

我的 s3 模块运行良好,很可能不是问题的一部分。

问题是我为每种尺寸返回了一个 ETag,但是当我查看我的 S3 管理控制台时,只存储了循环的最后一项(尺寸为“k”)。

有人可以帮帮我吗?

【问题讨论】:

标签: node.js amazon-web-services amazon-s3 coffeescript aws-sdk


【解决方案1】:

就像@RistoNovic 所说,我必须使用异步循环和async 模块的forEachOf 函数。

uploadSize = (val, key, callback) ->
  newPhotoImg
  .resize null, val
  .toBuffer 'jpg', (err, buffer) ->
    if err then callback err else
      params =
        Key: newPhoto.id + '/' + newPhoto.id + '-' + key + '.jpg'
        Body: buffer
        ContentType: 'image/jpeg'
      s3.putObject params, (err, data) ->
        if err then callback err else callback()

async.forEachOf sizes, uploadSize, (err) ->
  if err then console.error err and res.status(500).send "Error with uploading image." else
    fs.unlinkSync process.cwd() + '/' + req.files.file.path
    newPhoto.save (err, doc) ->
      if err then console.error and res.status(500).send "Error with saving photo." else
        res.send doc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-23
    • 1970-01-01
    相关资源
    最近更新 更多