Save Image in VARBINARY with C # ASP.NET

0

How do I get an image received on a Form of HTML and write to the bank in VARBINARY with C# ?

I'm using C# ASP.NET MVC5 CORE .

    
asked by anonymous 30.11.2017 / 11:24

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 stream and then pro byte [] and then save 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);
            //Recebo o stream, passo pra bytearray
            byte[] barray  = memoryStream.ToArray();
            //passo o array para o objeto
            obj.Foto = barray;

        }

        await _context.MyObjects.AddAsync(obj);
        _context.SaveChanges();
     }

     return View("Index");
}

Remember, in the form, add the property enctype="multipart / form-data" I hope I have helped.

Edit. I put it first to write as a string (varchar) and not varbinary. Fixed.

    
30.11.2017 / 11:29
0

I tried to use the code:

[HttpPost]
    public ActionResult UploadFile(HttpPostedFileWrapper file)
    {
        FileStream fs = new FileStream(Convert.ToString(file), FileMode.Open, FileAccess.Read);
        BinaryReader br = new BinaryReader(fs);

        byte[] imagemArray = br.ReadBytes((int)fs.Length);

        br.Close();
        fs.Close();

        return View("UploadFile");

    }

But I do not know what type of action to get the HTML file, I've already tried string and HttpPostedFileBase, but it does not work.

    
30.11.2017 / 12:31