Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ByteArray to IFormFile

I am developing some REST API with C# and Net Core
I have a function in my repository which accepts a parameter of type IFormFile.

public async Task<bool> UploadFile(IFormFile file)
{
    // do some stuff and save the file to azure storage
}

This function is called by a controller method which pass it the uploaded file

public class FileController : Controller
{
    public async Task<IActionResult> UploadDoc(IFormFile file
    {
        // Call the repository function to save the file on azure
        var res = await documentRepository.UploadFile(file);
    }
}

Now I have another function that calls an external API which returns a file as a byte array. I'd like to save this byte array using the repository.UploadFile method but I can't cast the byte array object to IFormFile.
Is it possible?

like image 803
skysurfer Avatar asked Oct 14 '19 14:10

skysurfer


People also ask

What is IFormFile C#?

What is IFormFile. ASP.NET Core has introduced an IFormFile interface that represents transmitted files in an HTTP request. The interface gives us access to metadata like ContentDisposition, ContentType, Length, FileName, and more. IFormFile also provides some methods used to store files.


1 Answers

You can convert the byte array to a MemoryStream:

var stream = new MemoryStream(byteArray);

..and then pass that to the constructor of the FromFile class:

IFormFile file = new FormFile(stream, 0, byteArray.Length, "name", "fileName");
like image 75
41686d6564 stands w. Palestine Avatar answered Oct 06 '22 00:10

41686d6564 stands w. Palestine