2016-08-02 56 views
1

似乎每个人都可以解释如何将文件发送到S3,但不幸的是,我还没有发现任何关于如何存储数据的信息S3回到我的Angular2 MEAN堆栈应用程序中。我猜这意味着我错过了一些简单的东西。如何构建S3上传器并通过aws-sdk检索S3数据

目前,我可以上传到S3,但几秒钟后我又回到了js对象,即使我已经尝试订阅bucket.upload,但我没有做任何事情来捕获s3存储桶信息。

有人能帮我看看我可能在这里失踪了吗?

这是我在做什么。

我的模板:

<div class="form-group" > 
<input type="file" (change)="uploadToS3($event)" #input /> 
</div> 

我的组件:

export class ProfileImgUploadComponent implements OnInit { 
// This class and template is to upload img to S3 and assign to profile 
@Input() profile: Profile; 
pic_main_loc = ''; 
file: File; 
items: any[] = []; 

policy: String; 
s3signature: String; 


constructor(private router: Router, private awsService: AWSUploadService, private http: Http) {} 

ngOnInit() { 
    //console.log(this.profile.first_name) 
} 

uploadToS3(file: any){ 

    require('aws-sdk/dist/aws-sdk'); 

    var AWS = window.AWS; 
    var file = file.target.files[0]; 

    AWS.config.credentials = new AWS.Credentials("myID", "MyPassword"); 

    var bucket = new AWS.S3({params: {Bucket: 'pcvidistorage1'}}); 
    var params = {Key: file.name, ContentType: file.type, Body: file, "x-amz-acl": "public-read"}; 


    console.log(params); 

    bucket.upload(params, function (err, data) 
    { 
     console.log(file.name); 
     console.log(err, data); 
     console.log('i am here'); 
     return data 
    }); 

} 

//Map file on change 
onChange(event) { 
    var files = event.srcElement.files; 
    this.file = files[0]; 
    console.log(this.file); 
} 
+0

您与暴露你的凭据: AWS.config.credentials =新AWS.Credentials( “AKIAJ2N2UW2T5YIL662Q”, “szwvBjPtJ0zvZeaBrIU7Yl/wuG7BKGHCQe + eCiyw”); 从安全角度来看这很糟糕 – AndroidLover

+0

感谢您的提示。这些都是幸运的老活跃证书,不知道我是如何错过的;) – JasonPerr

回答

0

搜索和黑客攻击这一段时间之后,这里是我想通了。

我创建了亚马逊凭证,看起来像这样一个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, '&lt;') 
      + '<br/><img src="' + data.Location.replace(/"/g, '&quot;') + '"/>') 
     .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时刻。