gpt4 book ai didi

c# - 从 IFormFile 异常中获取内存流

转载 作者:行者123 更新时间:2023-12-05 05:02:06 26 4
gpt4 key购买 nike

我上传了一张图片并想将它发送到第三方服务(Cloudinary)而不将文件保存在我的服务器中。

public async Task<List<string>> GetImagesUrlsByImage(IFormFile image)
{
List<string> urlList = new List<string>();
ImageUploadParams uploadParams = new ImageUploadParams();

using (var memoryStream = new MemoryStream())
{
await image.CopyToAsync(memoryStream);
uploadParams.File = new FileDescription(image.FileName, memoryStream);
uploadParams.EagerTransforms = new List<Transformation>
{
new EagerTransformation().Width(200).Height(150).Crop("scale"),
new EagerTransformation().Width(500).Height(200).Crop("scale")
};

ImageUploadResult result = await _cloudinary.UploadAsync(uploadParams);
var url = result.SecureUrl.ToString();
urlList.Add(url);
}

return urlList;
}

我没有得到异常,但来自 Cloudinary 的结果消息有一条错误消息:“无图像”;

调试时我看到这些错误:

enter image description here

我需要在此代码中修复什么?

最佳答案

最有可能的是,假设其他一切正常,您只需在 MemoryStream 中重置光标位置:

   ms.Position = 0;

如此完整的例子:

public async Task<List<string>> GetImagesUrlsByImage(IFormFile image)
{
List<string> urlList = new List<string>();
ImageUploadParams uploadParams = new ImageUploadParams();

using (var memoryStream = new MemoryStream())
{
await image.CopyToAsync(memoryStream);

ms.Position = 0; // set cursor to the beginning of the stream.

uploadParams.File = new FileDescription(image.FileName, memoryStream);
uploadParams.EagerTransforms = new List<Transformation>
{
new EagerTransformation().Width(200).Height(150).Crop("scale"),
new EagerTransformation().Width(500).Height(200).Crop("scale")
};

ImageUploadResult result = await _cloudinary.UploadAsync(uploadParams);
var url = result.SecureUrl.ToString();
urlList.Add(url);
}

return urlList;
}

关于c# - 从 IFormFile 异常中获取内存流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62388617/

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