gpt4 book ai didi

C# MVC/API - 从 Amazon S3 为我的 API 调用返回图像

转载 作者:行者123 更新时间:2023-11-30 12:20:20 26 4
gpt4 key购买 nike

我正在使用 .net core 从私有(private) Amazon S3 存储桶上传和检索图像。

我能够成功上传它,甚至在我从 S3 下载它之后查看它,但是当我有点不确定如何将流/响应返回给客户端以进行实际的 API 调用时(对于现在的示例我只是尝试使用 Postman/Fiddler 代理工具从我的 API 取回图像)

我的 S3 检索流的代码:

///Retrieve my image from my bucket

public async Task<string> ReadObjectData(MediaFolder key, String fileName)
{
string responseBody = "";
IAmazonS3 client;

using (client = new AmazonS3Client(accessKey, accessSecret, endpoint))
{
Amazon.S3.Model.GetObjectRequest request = new Amazon.S3.Model.GetObjectRequest
{
BucketName = bucket,
Key = key + "/" + fileName,
};
using (GetObjectResponse response = await client.GetObjectAsync(request))
using (Stream responseStream = response.ResponseStream)
using (StreamReader reader = new StreamReader(responseStream))
{
string title = response.Metadata["x-amz-meta-title"];
responseBody = reader.ReadToEnd();
}
}
return responseBody;
}

所以现在在我的 Controller 中,我有以下操作:

   [HttpGet("ProfilePic")]
public async Task<IActionResult> GetProfilePicture()
{
var user = await GetUserFromBearerToken();

//Retrieve
var utf8ImageResponse = await _fileService.ReadObjectData(MediaFolder.Profiles, user.ProfileImageFileName);

//To return a file as a stream
var imageBytes = System.Text.Encoding.UTF8.GetBytes(utf8ImageResponse);

//Return the image, which I'll hardcode as jpeg for a test
return File(imageBytes, "image/jpeg");
}

当我使用 Postman 进行调用时,它会返回一个小空白框(如果您尝试返回图像,您会看到该框,但它不是有效图像或在某种程度上为 null)。

现在我正在使用 Postman,但理想情况下我想要一个应用来呈现这张图片。

知道我做错了什么吗?我尝试搞乱 base64 编码和其他东西,但似乎没有任何效果。

谢谢!

最佳答案

这样你就可以从 S3 存储中以流的形式检索文件

public async Task<Stream> ReadObjectData(MediaFolder key, String fileName)
{
try
{
using (var client = new AmazonS3Client(accessKey, accessSecret, endpoint))
{
var request = new GetObjectRequest
{
BucketName = bucket,
Key = key + "/" + fileName
};

using (var getObjectResponse = await client.GetObjectAsync(request))
{
using (var responseStream = getObjectResponse.ResponseStream)
{
var stream = new MemoryStream();
await responseStream.CopyToAsync(stream);
stream.Position = 0;
return stream;
}
}
}
}
catch (Exception exception)
{
throw new Exception("Read object operation failed.", exception);
}
}

然后 - 将此流作为 FileStreamResult 返回:

[HttpGet("ProfilePic")]
public async Task<IActionResult> GetProfilePicture()
{
var user = await GetUserFromBearerToken();

Stream imageStream = await _fileService.ReadObjectData(MediaFolder.Profiles, user.ProfileImageFileName);

Response.Headers.Add("Content-Disposition", new ContentDisposition
{
FileName = "Image.jpg",
Inline = true // false = prompt the user for downloading; true = browser to try to show the file inline
}.ToString());

return File(imageStream, "image/jpeg");
}

关于C# MVC/API - 从 Amazon S3 为我的 API 调用返回图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52412517/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com