我正在尝试将名为“quotes.png”的图像上传到我的Ionic 2应用程序中的s3存储桶(没有使用节点),但它显示“网络故障”。
这就是我的代码的样子(省略了敏感信息):
import AWS from 'aws-sdk';
import S3 from 'aws-sdk/clients/s3';
AWS.config.update({ accessKeyId: 'myaccesskeyid', secretAccessKey: 'mysecretaccesskey' })
var s3 = new AWS.S3();
var params = {
Bucket: 'mybucketname',
Key: 'assets/img/quotes.png',
Body: "hello"
};
s3.putObject(params, function (err, res) {
if (err) {
console.log(err);
} else {
debugger;
console.log("Successfully uploaded data to myBucket/myKey");
}
});
(更新)这是错误的详细信息:
XMLHttpRequest cannot load https://mybucket-name.s3-ap-southeast-
1.amazonaws.com/assets/img/quotes.png. Response to preflight request doesn't
pass access control check: No 'Access-Control-Allow-Origin' header is
present on the requested resource. Origin 'http://localhost:8100' is
therefore not allowed access. The response had HTTP status code 403.
Error: Network Failure
at XMLHttpRequest.<anonymous> (xhr.js:52)
at t.invokeTask (polyfills.js:3)
at Object.onInvokeTask (ng_zone.js:227)
at t.invokeTask (polyfills.js:3)
at e.runTask (polyfills.js:3)
at XMLHttpRequest.invoke (polyfills.js:3)
注意:我不在我的Ionic 2应用程序中使用节点js。我正在使用Parse JavaScript SDK,AWS S3,AWS EC2,Elastic beanstalk和Ionic 2与Angular 2。
所以问题是:我是否正确编写了代码/我的代码有问题吗?谢谢 :)
您需要在AWS.config中指定存储桶所在的区域。
例:
AWS.config.update({region:'us-west-2'});
在调用新AWS.S3()之前插入此行。
这是在aws中使用s3存储桶上传图像的最新代码
var AWS = require('aws-sdk');
var fs = require('fs');
var path = require('path');
var multerS3 = require('multer-s3');
AWS.config.update({
accessKeyId: "",
secretAccessKey: "",
region:''
});
router.post('/upload_images_s3', upload.single('image'), (req,res,next) => {
res.json('Successfully uploaded files!')
});
var maxSize = 1024 * 1024 * 50;
var rootFolder = path.resolve(__dirname, './');
var s3 = new AWS.S3({params: {Bucket: 'keyfi'}});
var upload = multer({
storage: multerS3({
s3: s3,
bucket: 'keyfi/images',
acl: 'public-read-write',
limits: {
fileSize: maxSize
},
metadata: function (req, file, cb) {
cb(null,{fieldName:file.originalname});
console.log(file);
},
key: function (req, file, cb) {
cb(null,file.originalname)
}
})
})