我正在尝试使用angular将文件直接上传到AWS S3。我在s3上有一个文件上传组件,它使用s3上传器和我在组件中导出的其他几个类。现在我想向成功展示toastr。我以为我会在这个函数中使用toastrService
upload(event) {
let file = event.srcElement.files[0];
this.uploader.upload(file).then(x => {
console.log(x);
});
console.log(this.config);
}
在组件内部,所以我可以在这里轻松使用toastrService,但是s3没有给我任何响应。它给了我204状态消息
我尝试过使用var toastr:Toastrservice:但它给了我undefined。 我的代码片段。
import { Component, OnInit } from "@angular/core";
import { Http } from "@angular/http";
import { StorageService } from "../../../shared/services/storage-service/storage.service";
import { ToastrService } from "ngx-toastr";
declare var CryptoJS: any;
declare var toastr: ToastrService;
@Component({
selector: "app-slots-upload",
templateUrl: "./slots-upload.component.html",
styleUrls: ["./slots-upload.component.css"]
})
export class SlotsUploadComponent implements OnInit {
color = "primary";
mode = "indeterminate";
value = 50;
bufferValue = 75;
currentUser;
uploader: S3Uploader;
imagePath: string;
config = new S3Config();
constructor(
private http: Http,
private storageService: StorageService,
// private toastr: ToastrService
) {
this.currentUser = JSON.parse(this.storageService.getToken());
console.log(this.currentUser);
if (this.currentUser.role === "Admin") {
this.config.accessKey = this.currentUser.accessKey;
this.config.bucket = this.currentUser.bucketNameSlot;
this.config.secretAccessKey = this.currentUser.secretKey;
this.config.region = this.currentUser.regionVal;
console.log(this.config);
}
this.uploader = new S3Uploader();
// Input your S3 Config
this.uploader.init(http, this.config);
}
upload(event) {
let file = event.srcElement.files[0];
this.uploader.upload(file).then(x => {
console.log(x);
});
console.log(this.config);
}
ngOnInit() {}
}
export class S3Config {
bucket: string;
accessKey: string;
secretAccessKey: string;
region: string;
folder: string;
}
export class S3Uploader {
private config: S3Config;
private http: Http;
private toastr: ToastrService;
init(http: Http, config: S3Config) {
this.http = http;
this.config = config;
}
upload(file: any): Promise<any> {
let date = this.generateTimestamp();
let datetime = date + "T000000Z";
let credential = `${this.config.accessKey}/${date}/${this.config.region}/s3/aws4_request`;
let policy = JSON.stringify({
expiration: new Date(Date.now() + 100000).toISOString(),
conditions: [
{ bucket: this.config.bucket },
["starts-with", "$key", ""],
{ acl: "public-read" },
["starts-with", "$Content-Type", ""],
{ "x-amz-credential": credential },
{ "x-amz-algorithm": "AWS4-HMAC-SHA256" },
{ "x-amz-date": datetime }
]
});
let policyBase64 = window.btoa(policy);
let signatureKey = this.generateSignatureKey(this.config.secretAccessKey, date, this.config.region, "s3");
let signature = CryptoJS.HmacSHA256(policyBase64, signatureKey).toString(CryptoJS.enc.Hex);
let formData = new FormData();
formData.append("acl", "public-read");
formData.append("Content-Type", file.type);
formData.append("X-Amz-Date", datetime);
formData.append("X-Amz-Algorithm", "AWS4-HMAC-SHA256");
formData.append("X-Amz-Credential", credential);
formData.append("X-Amz-Signature", signature);
formData.append("Policy", policyBase64);
formData.append("key", file.name);
formData.append("file", file);
return new Promise((resolve, reject) => {
this.http
.post(
`https://${this.config.bucket}.s3.amazonaws.com/`,
formData
)
.subscribe(
x => {
console.log(x);
if ( x.status === 204) {
console.log('success');
// console.log(this.toastr);
console.log(toastr);
}
// this.toastr.success("uploaded");
resolve(x.headers.get("Location"));
},
x => {
console.error(x);
reject();
}
);
});
}
generateSignatureKey(key, dateStamp, regionName, serviceName) {
let kDate = CryptoJS.HmacSHA256(dateStamp, "AWS4" + key);
let kRegion = CryptoJS.HmacSHA256(regionName, kDate);
let kService = CryptoJS.HmacSHA256(serviceName, kRegion);
let kSigning = CryptoJS.HmacSHA256("aws4_request", kService);
return kSigning;
}
generateTimestamp() {
let date = new Date();
let year = date.getFullYear();
let month = ("0" + (date.getMonth() + 1)).slice(-2);
let day = ("0" + date.getDate()).slice(-2);
return year + month + day;
}
}
答案 0 :(得分:0)
在S3Uploader中添加以下代码:
constructor(
private toastr: ToastrService
)
并在S3Uploader类上使用@Inject()装饰器。 @Inject()装饰器将告诉angular在您的类中使用依赖注入,并将提供ToastrService的实例。
使用以下代码行显示烤面包机:
this.toastr.success("your message");