0

我从 3rd 方 API 接收一组对象,我想将其数据存储到 JSON 文件中的 S3 存储桶。以下是我想要实现的步骤

1> 在 S3 存储桶中创建新的 JSON 文件我有以下内容:

var AWS = require('aws-sdk')
var express = require('express')
var multer = require('multer')
var multerS3 = require('multer-s3')
AWS.config.loadFromPath('./lib/configFile.json');
var s3 = new AWS.S3();
var data =  [
             {
              name: abc,
              address: xyz, def-12345
             },{
              name: fgh,
              address: cvb, def-09876
             },{
              name: jkl,
              address: nbm, def-34566
             }
            ]

现在,我想将此数据作为 JSON 文件上传到 S3 存储桶中。 有没有办法将这些数据上传到 S3 而无需在路径中创建任何临时 json 文件并将这些数据直接存储到 S3。

2> 在 S3 上已经有 JSON 文件:假设我在 S3 存储桶上已经有 JSON 文件,我想更新同一个文件。因此,要实现这一点,有什么方法可以直接将 JSON 数据临时存储在某处并更新此文件。

实现这一目标的最佳方法是什么?

4

1 回答 1

3

我知道这已经晚了。但我的评论可能对其他人有所帮助。

几天前,即使我也遇到了同样的情况。我有一个巨大的 javascript 对象。我寻找解决方案。然后我看这里

我创建了一个通用函数来上传可能是缓冲区、base64 或 JSON 数据的文件。

let data = {
  version: "2.3.4",
  objects: [{
    a: "imagas dae",
    verasdasdsion: "2.3.4",
    originX: "center",
    originY: "center"
  }],
  background: "#232326",
  canvasWidth: 619,
  canvasHeight: 413
}
uploadFile(JSON.stringify(data), 'test.json').then(r=>{}).catch(e=>{})



function uploadFile(file, file_name, path = '/defualt') {
    return new Promise((resolve, reject) => {
        if (Buffer.isBuffer(file) || (file && Buffer.isBuffer(file.buffer)) || String(file_name).includes('.json') || file.indexOf('data:') === 0) {
            file = Buffer.isBuffer(file) ? file : String(file_name).includes('.json') ? file : file.indexOf('data:') === 0 ? new Buffer(img_src.replace(/^data:\w+\/\w+;base64,/, ""), 'base64') : file.buffer;
            var data = {
                Key: file_name,
                Body: file,
                Bucket: "path/to/your/bucket" + path,
                CacheControl: 'no-cache'
            };


            if (file.indexOf('data:') === 0) {
                data['ContentType'] = String(file).substr(file.indexOf('data:') + 'data:'.length, file.indexOf(';'))
            } else if (String(file_name).includes('.json')) {
                data['ContentType'] = 'application/pdf';
            }

            s3.putObject(data, function (err, data) {
                if (err) {
                    console.log('Error uploading data: ', err);
                    return reject(err);
                } else {
                    return resolve({
                        name: file_name,
                        path: path
                    });
                }
            });
        } else {
            return reject('File is required');
        }
    });
}
于 2018-12-04T13:35:13.117 回答