如何使用nodejs在亚马逊s3上传图像并公开

时间:2016-03-04 04:28:27

标签: node.js amazon-s3 aws-sdk

我使用以下代码在亚马逊S3上传图像,但它不公开。我需要传递什么其他参数才能公开。

var AWS = require('aws-sdk');
AWS.config.region = 'us-west-2';

var s3bucket = new AWS.S3({params: {Bucket: 'myBucket'}});
s3bucket.createBucket(function() {
var params = {Key: 'myKey', Body: 'Hello!'};
s3bucket.upload(params, function(err, data) {
if (err) {
  console.log("Error uploading data: ", err);
} else {
  console.log("Successfully uploaded data to myBucket/myKey");
}
});
});

3 个答案:

答案 0 :(得分:1)

在s3存储桶上传数据时公开资源。我可以从任何地方下载该链接。

试一试:

var s3bucket = new AWS.S3({
  region: Constant.AWS_S3_REGION
 });
 console.log(filename);
 var params = {
  Key: filename,
  Body: fs.createReadStream(filepath),
  Bucket: Constant.AWS_S3_BUCKET,
  ACL:'public-read-write'
 };
s3bucket.upload(params, cb)

干杯... !!!!

答案 1 :(得分:0)

要在您的存储分区中公开数据,请转换以下内容:

var params = {Key: 'myKey', Body: 'Hello!'};

以下:

var params = {Key: 'myKey', Body: 'Hello!', ACL: 'public-read'};

为了更好地理解,请按照This Good Tutorial

进行操作

快乐帮助!

答案 2 :(得分:0)

抱歉,我之前的代码是

var express = require('express');

var app = express();

var bodyParser = require('body-parser');

app.use(bodyParser.json()); // support json encoded bodies

app.use(bodyParser.urlencoded({ extended: true })); 

var multipart = require('connect-multiparty');

var multipartMiddleware = multipart();

var fs = require('fs'),
    S3FS = require('s3fs'),
    s3fsImpl = new S3FS('****', {
    accessKeyId: '***',
    secretAccessKey: '**********'
});

// Create our bucket if it doesn't exist
s3fsImpl.create();

app.post('/api',multipartMiddleware, function (req, res) {

res.send(req.body, req.files);

var file = req.files.file;

var stream = fs.createReadStream(file.path);

return s3fsImpl.writeFile(file.originalFilename, stream).then(function () {

    fs.unlink(file.path, function (err) {
        if (err) {
            console.error(err);
        }
    });
    res.status(200).end();
});
});