我试图将文件(确切地说是图片)上传到Cloudinary。 在Cloudinary的.NET文档(Documentation)中,它说文件应该像这样上传:
var uploadParams = new ImageUploadParams()
{
File = new FileDescription(@"c:\sample.jpg")
};
var uploadResult = cloudinary.Upload(uploadParams);
基本上,我需要文件路径来上传图像。当我对其工作的路径进行硬编码时,我希望用户能够选择自己的文件。 获取我发现的文件的唯一方法是使用IFormFile,但我可以使用它上传文件的唯一方法是首先将其上传到服务器,然后获取上传文件的路径并将其转发给Cloaudinary,但是必须是更好的方式。
那么如何让用户使用ASP.NET Core将文件上传到Cloudinary?
答案 0 :(得分:6)
基本上,Cloudinary允许您从路径或Streams上传文件。
对于文件路径:
var uploadParams = new ImageUploadParams()
{
File = new FileDescription(@"c:\sample.jpg")
};
var uploadResult = cloudinary.Upload(uploadParams);
For Stream:
HttpPostedFile file = fileInput.PostedFile;
var uploadParams = new ImageUploadParams()
{
File = new FileDescription(file.FileName, file.InputStream),
};
var uploadResult = cloudinary.Upload(uploadParams);
第二种方法允许您甚至发布包含图像数据的byte []图像内容或Base64字符串,您可以轻松将其转换为Stream以进行上传。
//data is a byte[]
Stream stream = new MemoryStream(data);
var cloudinary = Connect();
var uploadParams = new ImageUploadParams()
{
File = new FileDescription(GetGuid.Short(), stream),
PublicId = GetGuid.Short()
};
var uploadResult = cloudinary.Upload(uploadParams);
return uploadResult.SecureUri.AbsoluteUri;
答案 1 :(得分:0)