直接从浏览器上传字符串到没有本地文件的s3

时间:2017-08-05 09:11:59

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

我正在使用javascript,node.js和aws sdk。有许多关于使用签名URL直接将现有文件上传到S3的示例,但现在我尝试上传字符串并在S3中创建文件,而不使用任何本地保存的文件。有什么建议吗?

3 个答案:

答案 0 :(得分:2)

请按照此处的示例操作 http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putObject-property

将您的字符串转换为缓冲区并传递它。它应该工作。

答案 1 :(得分:1)

您可以尝试这样的事情:

var fs = require('fs');
exports.upload = function (req, res) {
    var file = req.files.file;
    fs.readFile(file.path, function (err, data) {
        if (err) throw err; // Something went wrong!
        var s3bucket = new AWS.S3({params: {Bucket: 'mybucketname'}});
        s3bucket.createBucket(function () {
            var params = {
                Key: file.originalFilename, //file.name doesn't exist as a property
                Body: data
            };
            s3bucket.upload(params, function (err, data) {
                // Whether there is an error or not, delete the temp file
                fs.unlink(file.path, function (err) {
                    if (err) {
                        console.error(err);
                    }
                    console.log('Temp File Delete');
                });

                console.log("PRINT FILE:", file);
                if (err) {
                    console.log('ERROR MSG: ', err);
                    res.status(500).send(err);
                } else {
                    console.log('Successfully uploaded data');
                    res.status(200).end();
                }
            });
        });
    });
};

答案 2 :(得分:0)

尚未尝试amazon-web-servicesamazon-s3aws-sdk,但如果您能够上传FileFormData个对象,则可以创建其中一个或两个JavaScript并上传对象。

// create a `File` object
const file = new File(["abc"], "file.txt", {type:"text/plain"});
// create a `Blob` object
// will be converted to a `File` object when passed to `FormData`
const blob = new Blob(["abc"], {type:"text/plain"});    
const fd = new FormData();
fd.append("file", blob, "file.txt");