I’m creating a Web App in c# and I need to upload an image from an html form into my database.
I tried to do it this way but the binaryformatter can’t be used in api controllers because of security issues.
[HttpGet("imageUploadEndpoint")]
public IActionResult bytesImage([FromForm] object image)
{
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, image);
//ms.ToArray() should then be uploaded to my sqlite database via entityframework in byte[] format
return Ok(ms.ToArray()); //this return was just to see what happened
}
—IMAGE UPLOAD TO API RESOLVED—
Now I need to put images inside an sqlite db with entityframework. How could I do it?
3
Answers
I solved the upload this way:
and i'll put the img object in the sqlite db as a BLOB data value.
Uploading an image to a GET endpoint is not a good idea because they have no request body and are not supposed to change the server state (MDN).
Instead, I would recommend you to use a POST endpoint and data binding to
IFormFileCollection
. I am using this inside of a standard MVC controller but don’t know whether it works in anApiController
, too.In one of my open source projects you can find the full implementation of an image upload with ASP.NET Core MVC (GitHub).
Update for storing in database
Although I would recommend to store photos as files, you could create an EF Core database context and an entity like this:
Now you can extend your controller:
My Solution is like –
I tried using minimal API (.net 7)
Below is the Model
{
public IFormFile? File { get; set; }
public static async ValueTask<Photo?> BindAsync(HttpContext context, ParameterInfo parameter)
{
var form = await context.Request.ReadFormAsync();
var file = form.Files["file"];
return new Photo
{
File = file
};
}
}
Also, my user profile data model is like this:
}
Then used minimal API endpoints: