Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 315
Offir Avatar asked Jan 18 '26 06:01

Offir


1 Answers

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;
}
like image 128
Nenad Avatar answered Jan 19 '26 19:01

Nenad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!