direct upload string from browser to s3 without local file

泪湿孤枕 提交于 2021-02-08 05:34:28

问题


I am using javascript, node.js and aws sdk. There are many examples about uploading existing files to S3 directly with signed URL, but now I am trying to upload strings and create a file in S3, without any local saved files. Any suggestion, please?


回答1:


Have not tried amazon-web-services, amazon-s3 or aws-sdk, though if you are able to upload File or FormData objects you can create either or both at JavaScript and upload the object.

// 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");



回答2:


Please follow the example here http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#putObject-property

Convert your string to buffer and pass it. It should work.




回答3:


You could try something like this:

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();
                }
            });
        });
    });
};


来源:https://stackoverflow.com/questions/45520205/direct-upload-string-from-browser-to-s3-without-local-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!