我正在尝试将登录名,密码和图片从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>
jquery ajax提交 -
var data = $('#login-form').serialize();
var url = $('#login-form').attr('action');
$.post(url, data, function (response) {
//some code here
}
控制器 -
[HttpPost]
public JsonResult Index(FormCollection data)
{
String userName = data["username"];
String userPassword = data["password"];
//I want to get that picture here
}
请建议。
答案 0 :(得分:4)
试试这个
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>
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
}
}
}
您可以使用数据类型-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" />