Search code examples
imageasp.net-coreasp.net-core-webapicloudinary

Empty File error while uploading images to Cloudianary using ASP.NET Core web API


I'm having issues uploading an image to Cloudinary using ASP.NET Core Web API. The method for uploading to Cloudinary receives the Image using an IFormFile then copies it to the stream. Then my Cloudinary Upload method is configured for uploading images to Cloudinary but i get an Error, Empty file when the upload method is called. Here is my code.

public class CloudinaryAPI
{
    private readonly Cloudinary cloudinary;

    /// <summary>
    /// Set up cloudinary account 
    /// </summary>
    /// <param name="cloud">Cloud name</param>
    /// <param name="apiKey">API Key</param>
    /// <param name="apiSecret">API Secret</param>
    public CloudinaryAPI(string cloud = "", 
        string apiKey = "", string apiSecret = "")
    {
        Account account = new Account
        {
            Cloud = cloud,
            ApiKey = apiKey,
            ApiSecret = apiSecret
        };

        this.cloudinary = new Cloudinary(account);
    }

    /// <summary>
    /// Upload image using a Stream
    /// </summary>
    /// <param name="tream"></param>
    /// <returns></returns>
    public async Task<ImageUploadResult> UploadImage(Stream stream)
    {
        if(stream != null)
        {
            var uploadParams = new ImageUploadParams()
            {
                File = new FileDescription(Guid.NewGuid().ToString(), stream)
            };
            var uploadResult = await cloudinary.UploadAsync(uploadParams);
            return uploadResult;
        }
        throw new ArgumentNullException(message: "Something went wrong while trying to process image", null);
    }
}

Here is the Controller Action Receiving the request.

    public async Task<IActionResult> UpdateProfilePicture(IFormFile 
    fileUpload)
    {
        using (Stream stream = new MemoryStream())
        {
            stream.Flush();
            stream.Position = 0;
            await fileUpload.CopyToAsync(stream);

            // Upload the file if less than 500KB

            if (stream.Length < 524288)
            {
                // Upload image to cloudinary
                await cloudinary.UploadImage(stream);
            }

Solution

  • I found out that i had to reset the position of the stream after copying it from the IFormFile.

    public async Task<IActionResult> UpdateProfilePicture(IFormFile 
    fileUpload)
    {
        using (Stream stream = new MemoryStream())
        {
            stream.Flush();
            await fileUpload.CopyToAsync(stream);
            stream.Position = 0;
    

    The stream.Position should be set to 0 after copying the file to the stream.