搜索和黑客攻擊這一段時間之後,這裏是我想通了。
我創建了亞馬遜憑證,看起來像這樣一個aconfig.json文件:
{ "accessKeyId": "*****YourAccessKey****", "secretAccessKey": "***YourSecretKey****" }
我感動的文件上傳到事物的節點側,因爲我確定它更有意義本地上傳,創建一個上傳對象,驗證文件是否符合標準,然後上傳到s3。 Node(ExpressJS)路由文件的內容與下面粘貼的文件類似。
router.post('/sendToS3', function(req, res) {
var fs = require('fs');
var multer = require('multer');
var AWS = require('aws-sdk');
var path = require('path');
var awsCredFile = path.join(__dirname, '.', 'aconfig.json');
console.log('awsCredFile is');
console.log(awsCredFile);
AWS.config.loadFromPath(awsCredFile);
var s3 = new AWS.S3();
var photoBucket = new AWS.S3({params: {Bucket: 'myGreatBucket'}});
var sampleFile = {
"_id" : 345345,
"fieldname" : "uploads[]",
"originalname" : "IMG_1030.JPG",
"encoding" : "7bit",
"mimetype" : "image/jpeg",
"destination" : "./public/images/uploads",
"filename" : "31a66c51883595e74ab7ae5e66fb2ab8",
"path" : "/images/uploads/31a66c51883595e74ab7ae5e66fb2ab8",
"size" : 251556,
"user" : "579fbe61adac4a8a73b6f508"
};
var filePathToSend = path.join(__dirname, '../public', sampleFile.path);
function uploadToS3(filepath, destFileName, callback) {
photoBucket
.upload({
ACL: 'public-read',
Body: fs.createReadStream(filepath),
Key: destFileName.toString(),
ContentType: 'application/octet-stream' // force download if it's accessed as a top location
})
// http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3/ManagedUpload.html#httpUploadProgress-event
.on('httpUploadProgress', function(evt) { console.log(evt); })
// http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3/ManagedUpload.html#send-property
.send(callback);
}
multer({limits: {fileSize:10*1024*1024}});
console.log('filePathToSend is ');
console.log(filePathToSend);
uploadToS3(filePathToSend, sampleFile.filename, function (err, data) {
if (err) {
console.error(err);
return res.status(500).send('failed to upload to s3').end();
}
res.status(200)
.send('File uploaded to S3: '
+ data.Location.replace(/</g, '<')
+ '<br/><img src="' + data.Location.replace(/"/g, '"') + '"/>')
.end();
});
console.log('uploading now...');
});
我ProfileInputComponent現在上有這種上傳方法
upload() {
console.log('this.createdProfile before upload');
console.log(this.createdProfile);
this.uploadFileService.makeFileRequest("http://localhost:3000/upload", this.createdProfile.profileId, this.filesToUpload)
.then(
(result) => {
this.imageUploaded = true;
this.uploadFile = result.obj.path;
},
(error) => {
console.log('We are in error');
console.error(error);
});
}
上傳-file.service內的makeFileRequest方法是這樣的:
makeFileRequest(url: string, profileId, files: Array<File>) {
const token = localStorage.getItem('token') ? '?token=' + localStorage.getItem('token') : '';
console.log('profileId in upload service is: ');
console.log(profileId);
const profileParam = 'profileId=' + profileId;
return new Promise((resolve, reject) => {
var formData: any = new FormData();
var xhr = new XMLHttpRequest();
for(var i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
console.log('xhr.status is 200');
resolve(JSON.parse(xhr.response));
} else {
console.log('xhr.status is NOT 200');
reject(xhr.response);
}
}
};
xhr.open("POST", url+token+'&'+profileParam, true);
xhr.send(formData);
});
}
所以在這一點上,該文件被上傳到本地位置。現在是當我將創建一個更多的服務調用我上面提到的節點方法。我知道這會工作,因爲節點方法是由該服務創建的實際JSON對象進行測試的。
這花了我一段時間才終於可以正常工作,但是如果你在下面設置路由,請更新sampleFile JSON以指向系統上的一個真實文件,並用Postman命中它,它將發佈一個文件到你的S3帳戶。
希望這會有所幫助。很高興回答這個問題,因爲我認爲我終於有了我的S3A時刻。
您與暴露你的憑據: AWS.config.credentials =新AWS.Credentials( 「AKIAJ2N2UW2T5YIL662Q」, 「szwvBjPtJ0zvZeaBrIU7Yl/wuG7BKGHCQe + eCiyw」); 從安全角度來看這很糟糕 – AndroidLover
感謝您的提示。這些都是幸運的老活躍證書,不知道我是如何錯過的;) – JasonPerr