On your model, you need a property of type IFormFile
:
public class MyModel
{
public IFormFile Arquivo {get;set;}
}
In your object, or POCO class, you need a property of type byte[]
:
public class MyObject
{
public byte[] Foto {get;set;}
}
And In your controller action, get Model, move to stream
and then to byte[]
and then saved on the bench:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Upload(MyModel model)
{
if (ModelState.IsValid)
{
MyObject obj = new MyObject();
using (var memoryStream = new MemoryStream())
{
await model.Arquivo.CopyToAsync(memoryStream);
obj.Foto = memoryStream.ToArray();
}
await _context.MyObjects.AddAsync(obj);
_context.SaveChanges();
}
return View("Index");
}
Don’t forget to add the property in the form enctype="multipart/form-data"
I hope I’ve helped.
imgLocation would be the physical location of the image ex: C: minhafoto.jpg, you will turn it into Stream..
– Evandro
In my case there is no physical location, not on the server. The image will come from the user’s browser.
– Diego Grossi
With this code you will have to save the image in a temporary folder to then send it
– Evandro
I can’t get the image that the html form receives and send directly to the bank?
– Diego Grossi
@Diegogrossi what are you using? Asp.NET Webforms, MVC, Core ?
– Rovann Linhalis
Rovann am using ASP.NET, MVC, Core
– Diego Grossi
I think you’re making a little mess. Creating blobs (Binary large Objects) in the bank is a great way to destroy performance, thinking about it was created, some years ago, this "make-believe" feature that you are saving a file in the bank. In fact you are setting a STREAM, ie taking an array of bytes (the file) sending to the database as if they were data and this identifies that the column type is a file and in practice saves the file in that path ai. This is much more efficient than saving in the bank but is "tranparente" to the developer
– jean