将图像从HTML表单发送到MVC 4控制器

s.k*_*aul 1 jquery html5 asp.net-mvc-4

我试图将登录名,密码和图片从html5表单发送到asp.net mvc4控制器。我能够在该控制器中获取登录名和密码值。如何获得图片并保存到数据库?

html表格-

<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>
Run Code Online (Sandbox Code Playgroud)

jQuery Ajax提交-

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

控制器-

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

请提出建议。

Nil*_*are 5

尝试这个

html表格-

  <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>
Run Code Online (Sandbox Code Playgroud)

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);

    }
Run Code Online (Sandbox Code Playgroud)

控制器-

[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
           }
         }
    }
Run Code Online (Sandbox Code Playgroud)

您可以使用数据类型-IMAGE或VARBINARY将二进制数据直接保存在数据库中并进行显示

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" />
Run Code Online (Sandbox Code Playgroud)