How to convert a file into byte array in memory?
As opposed to saving the data as a string (which allocates more memory than needed and might not work if the binary data has null bytes in it), I would recommend an approach more like
foreach (var file in files)
{
if (file.Length > 0)
{
using (var ms = new MemoryStream())
{
file.CopyTo(ms);
var fileBytes = ms.ToArray();
string s = Convert.ToBase64String(fileBytes);
// act on the Base64 data
}
}
}
Also, for the benefit of others, the source code for IFormFile
can be found on GitHub
C# read IFormFile into byte[]
You can't open an IFormFile
the same way you would a file on disk. You'll have to use IFormFile.OpenReadStream()
instead. Docs here
public async Task<ActionResult> UploadDocument([FromForm]DataWrapper data)
{
IFormFile file = data.File;
long length = file.Length;
if (length < 0)
return BadRequest();
using var fileStream = file.OpenReadStream();
byte[] bytes = new byte[length];
fileStream.Read(bytes, 0, (int)file.Length);
}
The reason that fileStream.Read(bytes, 0, (int)file.Length);
appears to be empty is, because it is. The IFormFile.Filename
is the name of the file given by the request and doesn't exist on disk.
Issue retrieving Image in bytes from Database to IFormFile from model class
One way would be to map the properties manually
using (var con = _connFactory())
{
con.Open();
return con.Query("SELECT * FROM RecipeImage WHERE RecipeId = @recipeId", new { recipeId })
.Select(x => new Image()
{
recipeId = x.RecipeId,
format = x.Format,
description = x.Description,
image = new FormFile(new MemoryStream(x.Image), 0, x.Image.Length, null, "MyFile." + x.Format, "")
})
.FirstOrDefault();
}
But probably you want to send the file alone if you want to display it on the web. Try navigating to the v1/recipe/image/xxx endpoint in the browser to see if the image loads.
[Route("v1/recipe/image/{recipeId}")]
[HttpGet()]
public async Task<IActionResult> GetImage(int recipeId)
{
var data = await con.QueryAsync<byte[]>("SELECT Image FROM RecipeImage WHERE RecipeId = @recipeId", new { recipeId })
return File(new MemoryStream(data), "image/jpeg", "SomeName.jpg");
}
Related Topics
Copy Few Items from One List to Another List of Same Type in C#
Passing a List of Objects into an MVC Controller Method Using Jquery Ajax
How to Check for a Valid Base64 Encoded String
How to Get User Browser Name ( User-Agent ) in ASP.NET Core
How to Wait Until Task Is Finished in C#
How to Fix Json.Net (Newtonsoft.Json) Runtime File Load Exception
Pass Variable in Json String in C#
Trying to Add Spaces Between Characters in a String in C#
Access Variables/Functions from Another Component
Copy Files With Authentication in C#
Asp.Net Core - Swashbuckle Not Creating Swagger.Json File
How to Count Rows Within Entityframework Without Loading Contents
Lambda Where Id Does Not Exist in Another List
C# File.Delete, File Being Used by Another Process
Using Enum and | as Dictionary Key
Controlling Datetime Parameter Formatting in Webapi 2