javascript - GET 请求图像后 AWS S3 上传,上传不正确

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

在使用 Node(使用 request-promise-native & aws-sdk 从另一个 URL 下载图像后,我尝试将图像上传到我的 AWS S3 存储桶):

'use strict';

const config = require('../../../configs');
const AWS = require('aws-sdk');
const request = require('request-promise-native');

AWS.config.update(config.aws);
let s3 = new AWS.S3();

function uploadFile(req, res) {

    function getContentTypeByFile(fileName) {
        var rc = 'application/octet-stream';
        var fn = fileName.toLowerCase();

        if (fn.indexOf('.png') >= 0) rc = 'image/png';
        else if (fn.indexOf('.jpg') >= 0) rc = 'image/jpg';

        return rc;
    }

    let body = req.body,
        params = {
            "ACL": "bucket-owner-full-control",
            "Bucket": 'testing-bucket',
            "Content-Type": null,
            "Key": null, // Name of the file
            "Body": null // File body
        };

    // Grabs the filename from a URL
    params.Key = body.url.substring(body.url.lastIndexOf('/') + 1);

    // Setting the content type
    params.ContentType = getContentTypeByFile(params.Key);

    request.get(body.url)
    .then(response => {
        params.Body = response;
        s3.putObject(params, (err, data) => {
            if (err) { console.log(`Error uploading to S3 - ${err}`); }
            if (data) { console.log("Success - Uploaded to S3: " + data.toString()); }
        });
    })
    .catch(err => { console.log(`Error encountered: ${err}`); });
} 

当我测试时上传成功,但是在尝试从我的存储桶中重新下载后图像无法显示。此外,我注意到在使用我的函数上传文件后,存储桶中列出的文件的文件大小比最初上传的图像大得多。我试图弄清楚我哪里出错了,但找不到哪里。感谢您的帮助。

最佳答案

尝试用文本编辑器打开错误文件,你会看到里面写了一些错误。 您可以尝试使用 s3.upload 而不是 putObject,它更适合流。

关于javascript - GET 请求图像后 AWS S3 上传,上传不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53601671/

相关文章:

javascript - 在固定位置显示随机图像

javascript - $ ('element' ,this.el)[0] 是什么意思?

mysql - 将数据从 MySql 同步到 DynamoDb

javascript - 单击时获取 href 的顶级主机名

mysql - Node js mysql结束连接

node.js - 跳过或禁用 Mongoose 模型 save() 调用的验证

node.js - Nodejs 应用程序中强制使用 NPM 版本

amazon-web-services - gitlab CI创建docker镜像并推送到AWS

amazon-web-services - ECS Fargate 任务无法访问另一个账户中的 s3

javascript - 使用 node.js 检查 gravatar 是否存在