簡體   English   中英

如何使用aws-sdk構建S3上傳器並在Angular2中檢索S3數據

[英]How do I build an S3 uploader and retrieve S3 data in Angular2 with the aws-sdk

似乎每個人都可以解釋如何將文件發送到S3,但遺憾的是我還沒有找到任何關於如何將S3中的數據存儲回我的Angular2 MEAN堆棧應用程序的內容。 我猜這意味着我錯過了一些簡單的東西。

目前,我可以上傳到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);
}

經過一段時間的搜索和黑客攻擊,這就是我想到的。

我創建了一個帶有amazon憑據的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);
    });
}

upload-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帳戶。

希望這可以幫助。 很高興回答有關此問題的任何問題,因為我覺得我終於有了我的s3 A Ha時刻。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM