C# Read Iformfile into Byte[]

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



Leave a reply



Submit