Search code examples
c#asp.net-corememorystreamcloudinary

Get memory stream from IFormFile exceptions


I upload an image and want to send it to a third party service(Cloudinary) without saving the file in my server.

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;
}

I don't get an exception but the result message from Cloudinary has an error message:"No image";

While debugging I see these errors:

enter image description here

What do I need to fix in this code?


Solution

  • Most likely, assuming everything else works fine, you just have to reset position of cursor in your MemoryStream:

       ms.Position = 0;
    

    So full example:

    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;
    }