Save Image to Database with C #

1

Hello

I've seen the example Upload image for picturebox and write to the database but I did not understand 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.

Can anyone help me?

    
asked by anonymous 28.11.2017 / 17:58

2 answers

1

In 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;}
}

E In the action of your controller, you receive the Model, pass% pro_de% and then% pro_de% and then save it to the bank:

    [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");
    }
  

Remember, in the form, add the property stream

I hope I have helped.

    
28.11.2017 / 18:55
-1

Try this way Diego:

// Obtaining URL of the file to download and destination path // of it

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

// Other code statements ...

// Downloading

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

Then you pass the pathFile

FileStream Stream = new FileStream(caminhoArquivo, FileMode.Open, FileAccess.Read);
    
28.11.2017 / 18:20