s.k.paul
s.k.paul

Reputation: 7291

Send an image from html form to mvc 4 controller

I am trying to send login name, password and a picture from an html5 form to asp.net mvc4 controller. I am able to get loginname and password value in that controller. How to get the picture there and save to database?

html form-

<form action="/Home/Index" id="login-form">
   <input type="text" name="username">
   <input type="password" name="password">
   <input type="file" name="photo" accept="image/*;capture=camera">
   <button type="submit">Submit</button>
</form>

jquery ajax submission-

var data = $('#login-form').serialize();
var url = $('#login-form').attr('action');
$.post(url, data, function (response) {
 //some code here
}

controller-

[HttpPost]
public JsonResult Index(FormCollection data)
{
    String userName = data["username"];
    String userPassword = data["password"];
    //I want to get that picture here
}

Please suggest.

Upvotes: 1

Views: 6550

Answers (1)

Nilesh Gajare
Nilesh Gajare

Reputation: 6398

try this

html form-

  <form id="login-form">
    <input type="text" name="username" id="username">
    <input type="password" id="password" name="password">
    <input type="file" name="photo" id="files" accept="image/*;capture=camera">
    <button type="submit" onclick="submitform()">Submit</button>
  </form>

jquery ajax-

function submitform(){
        var postdata = $('#login-form').serialize();          
        var file = document.getElementById('files').files[0];
        var username = document.getElementById('username').value;
        var password = document.getElementById('password').value;
        var fd = new FormData();
        fd.append("files", file);
        fd.append("username", username);
        fd.append("password", password);
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "/Home/Index", false);
        xhr.send(fd);

    }

controller-

[HttpPost]
    public JsonResult Index(FormCollection data)
    {
        String userName = data["username"];
        String userPassword = data["password"];

      if (Request.Files["files"] != null)
        {
          using (var binaryReader = new BinaryReader(Request.Files["files"].InputStream))
           {
             var   Imagefile = binaryReader.ReadBytes(Request.Files["files"].ContentLength);//your image
           }
         }
    }

you can directly save binary data in database with datatype-IMAGE OR VARBINARY and to dispaly

string imageBase64 = Convert.ToBase64String(YOUR BINARY IMAGE FROM DB);
string imageSrc = string.Format("data:image/gif;base64,{0}", imageBase64);
<img src="@imageSrc" width="100" height="100" />

Upvotes: 6

Related Questions