-2

I need to store the image in my database in byte[]

I am sending the image from Javascript to mvc controller using ajax

In my javascript

var files = $("#MyImage").get(0).files;
formData.append('files', files);

in my MVC Controller

using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
        fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}

Is it a correct way to store the image or I am doing this wrong?

please suggest

3
  • Can you show the code how you pass the image from view to controller? Commented Oct 19, 2018 at 7:27
  • Use this code, perhaps it might be helpful stackoverflow.com/a/3947318/6124847 Commented Oct 19, 2018 at 7:38
  • Easy way to determine if it is a right way: Do you receive the image as a byte array in your database? Then Yes. If Not. Debug and then tell us where the problem is Commented Oct 19, 2018 at 8:03

1 Answer 1

0

You can post HttpPostedFileBase on your razor.

if (upload != null)
{
    using (var inputStream = upload.InputStream)
    {
        var memoryStream = inputStream as MemoryStream;
        if (memoryStream == null)
        {
            memoryStream = new MemoryStream();
            inputStream.CopyTo(memoryStream);
        }
        var data = memoryStream.ToArray();
}

The method signature should be like this

[HttpPost]
public ActionResult Foo(HttpPostedFileBase upload)
{
}

And your razor side:

@using (Html.BeginForm("Foo", "ControllerName", FormMethod.Post, new { @enctype = "multipart/form-data" }))
{

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.