.NET Min API Lambda经API Gateway返回S3 PDF至Angular仅本地可用
API Gateway触发Lambda返回PDF异常问题
本地运行正常,但通过API Gateway部署到云端后,前端下载的PDF打开提示"File does not begin with '%PDF-'"。Windows环境下,本地启动Angular前端和.NET Min API后端(双localhost)时,PDF下载始终正常。
.NET代码
Controller
[HttpGet("DownloadPDF")] public async Task<IActionResult> DownloadPDF(string filepath) { /* * How To Contribute * Call the DownloadPDF function. Pass in your S3 bucket's name and the object's name, or filepath, you want to retrieve. */ //Create a memory stream. MemoryStream memoryStream = new MemoryStream(); //Get PDF from S3 in binary form. using (var getPDFResponseStream = await _domain.DownloadPDF(Environment.GetEnvironmentVariable("bucketName"), filepath)) { //Copy bytes from start position 0 to end position y. await getPDFResponseStream.CopyToAsync(memoryStream); } //Reset the Position property to the beginning. memoryStream.Seek(0, SeekOrigin.Begin); //Return the binary to the front end. return File(memoryStream, MediaTypeNames.Application.Pdf, "dummyPDF.pdf"); }
Domain
public async Task<Stream> DownloadPDF(string bucketName, string filePath) { /* * How To Contribute * The filePath string must equal the object name inside the s3 bucket. */ return (await AmazonS3Service.DownloadObjectFromBucketAsync(bucketName, filePath)).ResponseStream; }
AmazonS3Service
public static async Task<GetObjectResponse> DownloadObjectFromBucketAsync( string bucketName, string objectName) { /* * Assume a valid IAM role with STS before making S3 call. */ var becomeAuthorizedForS3 = await AmazonSTSService.AssumeRoleAsync(Environment.GetEnvironmentVariable("roleToBeAssumed")); //Create an AmazonS3Client using AmazonS3Client s3Client = new AmazonS3Client(becomeAuthorizedForS3.Credentials.AccessKeyId, becomeAuthorizedForS3.Credentials.SecretAccessKey, becomeAuthorizedForS3.Credentials.SessionToken, Amazon.RegionEndpoint.USEast1); // Create a GetObject request. var request = new GetObjectRequest { BucketName = bucketName, Key = objectName, }; // Issue request and return control to calling method. return await s3Client.GetObjectAsync(request); }
Angular代码
HTTP Service
downloadPDF$ = (filePath: string | undefined) => { const url = `${this.basePath}${this.downloadPDFResource}?filePath=${filePath}`; return this.http.get(url, {responseType: 'blob'}) }
Component Method
downloadPDF() { let mockFilePath = 'sample_w2.pdf'; this.taxService.downloadPDF$(mockFilePath).subscribe({ next: (pdfDataLump: Blob) => { saveAs(pdfDataLump, mockPageLink) //npm i file-saver }, }); }
尝试过在Notepad++中编辑下载的PDF,在编码字符串前添加'%PDF-',但结果PDF损坏,提示"This file is damaged and could not be repaired."。
内容的提问来源于stack exchange,提问作者InstructionDecode
相关产品推荐
相关产品推荐

