Save Image in Database with C#

Asked

Viewed 1,487 times

1

Hello!

I saw the example Upload image to picturebox and write to database but I didn’t get that part:

FileStream Stream = new FileStream(imgLocation, FileMode.Open, FileAccess.Read);

What would this imgLocation be?

I’m getting the image of an html form.

Someone can help me?

  • imgLocation would be the physical location of the image ex: C: minhafoto.jpg, you will turn it into Stream..

  • In my case there is no physical location, not on the server. The image will come from the user’s browser.

  • With this code you will have to save the image in a temporary folder to then send it

  • I can’t get the image that the html form receives and send directly to the bank?

  • @Diegogrossi what are you using? Asp.NET Webforms, MVC, Core ?

  • Rovann am using ASP.NET, MVC, Core

  • 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

Show 2 more comments

2 answers

1

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.

  • I remove the code snippet from the controller I had informed in the question?

  • yes, no need to mess with filestream

-1

Try like this Diego:

// Getting URL of the file to be downloaded and destination path // of the same

string urlArquivo =
    "http://www.minhapagina.com.br/imagens/foto.png";
string caminhoArquivo = 
    @"C:\Temp\Downloads\foto.png";

// Other code instructions...

// Downloading

System.Net.WebClient client =
    new System.Net.WebClient();
client.DownloadFile(urlArquivo, caminhoArquivo);

Then you pass the wayArch

FileStream Stream = new FileStream(caminhoArquivo, FileMode.Open, FileAccess.Read);
  • Evandro apparently the function was able to read the image, but now I have permission problems in the folder I created to receive the image on the computer. I use the computer in the company domain with the company login and Visual Studio use the account of the Hotmail that is not in the company domain.

  • now it is giving another error: System.IO.Filenotfoundexception: Could not find file 'C: Program Files (x86) IIS Express Logo.jpg'.

  • you have to fix the path, it has to look like this @"C: Temp Downloads Logo.jpg! the image is in the folder?

  • This code is downloading the file, not uploading it

  • the path I created was: C: imgTemporarias Logo.jpg. There’s this image Logo.jpg, but it’s generating this error

  • I need you to download the image that the user passes in the HTML form

  • 1

    if the user passes an image in the html form, you should upload it to the server, not download it

  • @Evandro, I was able to take an image on the web and save it in the folder I created, now how do I take this image in the folder or its path and show the image in the html page?

  • <img src="caminho da imagem" /> but totally out of the question

  • I guess I couldn’t express myself well in the question @Rovannlinhalis, but I already got the image too.

  • @Evandro, I can only take images from the web, I can’t pass images that are on my machine.

Show 6 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.