Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert FormFile to Stream

I am doing an ASP .NET Core MVC web application. There is a module in the web application to upload a file to blob storage.

Following is the function I employ to upload a file to the blob storage:

public CloudBlockBlob UploadBlob(string BlobName, string ContainerName, IFormFile file)
{
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    CloudBlobContainer container = blobClient.GetContainerReference(ContainerName.ToLower());
    CloudBlockBlob blockBlob = container.GetBlockBlobReference(BlobName);

    try
    {
        blockBlob.UploadFromStreamAsync((Stream) file); //trying to convert FormFile to Stream type object and upload to blob storage
        return blockBlob;
    }
    catch (Exception e)
    {
        var r = e.Message;
        return null; 
    }
}

There, I have already cast the FormFile object 'file' to Stream object as given in the try block.
But instead of uploading the file to the blob storage, gives the Exception:

Unable to cast object of type 'Microsoft.AspNetCore.Http.FormFile' to type 'System.io.stream'

Question:
Is it possible to cast an IFormFile object to Stream or Is there any other proper way to do it?

Thank you.

PS: To get an input file I have to use FormFile type object, but to upload file to the blob storage I have to use Stream type object. So, to solve the issue anyhow I have to convert the input FormFile to an Stream type object.

like image 478
Pawara Siriwardhane Avatar asked Aug 22 '26 23:08

Pawara Siriwardhane


2 Answers

To convert FormFile to stream :

var stream = [YourFormFile].OpenReadStream();
like image 165
Munna Basha G Avatar answered Aug 25 '26 12:08

Munna Basha G


    blockBlob.UploadFromStreamAsync(file.Openreadstream());

https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.iformfile.openreadstream?view=aspnetcore-5.0

like image 32
Anton Christiansen Avatar answered Aug 25 '26 11:08

Anton Christiansen