【问题标题】:Download an image from its url and directly upload it to AWS从其 url 下载图像并直接上传到 AWS
【发布时间】:2016-08-23 15:00:38
【问题描述】:

我的问题找不到令人满意的答案。给定一个图像 url,我想下载它(不将其保存到磁盘)并立即将其上传到 AWS 存储桶。这是我的代码:

  self.downloadImage = function(url){
        let response = HTTP.get(url, {
            encoding:null // for binary
        })
        if (!response.headers['content-type'].split('/')[0] == 'image'){
            throw new Error("not an image")
        }
        return {
            data : response.content,
            contentType : response.headers['content-type']
        }
    }

    self.uploadImage = function(websiteName, imgUrl, callback){
        // we retrieve the image
        let image = downloadImage(imgUrl)
        let imageName = self.extractImageName(imgUrl)
        let filename = 'img/' +websiteName + "/" + imageName
        let newUrl = `https://s3.${Meteor.settings.AWS.REGION}.amazonaws.com/${Meteor.settings.S3.BUCKET_NAME}/${filename}`
        // makes the async function sync like
        let putObjectSync = Meteor.wrapAsync(s3Client.putObject, s3Client)
        try{
            let res = putObjectSync({
                Body: image.data,
                ContentType : image.contentType,
                ContentEncoding: 'base64',
                Key: filename,
                ACL:'public-read',
                Bucket: Meteor.settings.S3.BUCKET_NAME
            })
            return newUrl
        } catch(e) {
            return null
        }
    }

一切正常,只是图像似乎已损坏。到目前为止我试过了:

  • 使用aldeed:http,以便在下载时将编码设置为null,这似乎是一个很好的图片策略

  • 不使用,直接将响应的文本内容作为上传正文传递

  • 在aws中添加base64编码

仍然损坏。我觉得非常接近解决方案,因为图像类型和文件大小正确,但仍然无法在浏览器或我的计算机上打印。关于如何正确编码/检索数据的任何想法?

【问题讨论】:

    标签: http amazon-web-services meteor download upload


    【解决方案1】:

    好的,我自己找到了答案:

    aldeed:meteor 允许在get 请求中添加responseType 参数。我们只需将此选项设置为buffer,以便我们将数据作为缓冲区。然后我们简单地给这个缓冲区,不做任何转换,作为上传函数的Body

    【讨论】:

      猜你喜欢
      • 2021-01-19
      • 1970-01-01
      • 2019-06-24
      • 2014-04-06
      • 2016-08-01
      • 1970-01-01
      • 2021-10-27
      • 2020-12-04
      • 1970-01-01
      相关资源
      最近更新 更多