要解决Angular 2通过签名URL损坏S3图像的问题,可以尝试以下方法:
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { AwsService } from './aws.service';
@Injectable()
export class ImageService {
constructor(private http: HttpClient, private awsService: AwsService) {}
getImageUrl(imageKey: string): Observable {
return this.awsService.getSignedUrl(imageKey)
.map(signedUrl => {
// 处理签名URL,确保不会损坏
return signedUrl.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=+$/, '');
});
}
}
在上面的代码中,我们使用awsService
来获取签名URL,并对URL进行处理,确保URL中不会包含任何会损坏的字符。
encodeURIComponent
对key进行编码:import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { AwsService } from './aws.service';
@Injectable()
export class AwsService {
constructor(private http: HttpClient) {}
getSignedUrl(imageKey: string): Observable {
const encodedImageKey = encodeURIComponent(imageKey); // 对key进行编码
return this.http.get(`your_aws_lambda_endpoint?imageKey=${encodedImageKey}`)
.map(response => response.json().signedUrl);
}
}
在上面的代码中,我们使用encodeURIComponent
对imageKey进行编码,确保签名URL中不会包含任何会损坏的字符。
通过上述两种方法的组合,可以确保Angular 2通过签名URL获取S3图像时不会损坏图像。