[英]MVC upload and save form image with Ajax
I have a form with 3 inputs (text, image, submit button). 我有一个带有3个输入(文本,图像,提交按钮)的表单。
@using (Html.BeginForm("Save", "User", FormMethod.Post, new {Id="Form1", enctype = "multipart/form-data"}))
{
<input id="FileUploadInput" name="Image" type="file"/>
<input id="FirstName" Name="FirstName">
<input type="submit" id="inputSubmit" value="Save" />
}
Now i want to submit this form from javascript with AJAX 现在,我想使用AJAX从javascript提交此表单
$("#inputSubmit").click(function (e) {
e.preventDefault();
var form = $("#Form1");
form.validate();
if (form.valid()) {
$.ajax({
url: "/User/Save",
data: form.serialize(),
type: "POST",
success: function (data) {
if (data === "") {
location.reload();
}
else {
$(".content").html(data);
$.validator.unobtrusive.parse($(".content"));
}
}
});
}
return false;
});
In my controller file i have. 在我的控制器文件中。
public ActionResult Save(UserProfileSettings settings)
{
var image = setings.Image
var name = settings.Firstname
}
My model 我的模特
public class UserProfileSettings
{
public string FirstName { get; set; }
public HttpPostedFileBase Image { get; set; }
}
The problem is that in my controller method i am getting settins.FirstName, but settings.Image is always null. 问题是在我的控制器方法中,我正在获取settins.FirstName,但是settings.Image始终为null。 I think, that with this method it is not possible to serialize image file. 我认为,使用这种方法无法序列化图像文件。
尝试使用jquery插件进行多重上传: http ://blueimp.github.io/jQuery-File-Upload/
As Darin Dimitrov suggested before, it's better to use jquery forms plugin . 正如Darin Dimitrov之前建议的那样 ,最好使用jquery表单插件 。 I have already posted this in my another answer here . 我在另一个答案已经张贴了这个位置 。
Quick Example 快速范例
View 视图
@using (Ajax.BeginForm("YourAction", "YourController", new AjaxOptions() { HttpMethod = "POST" }, new { enctype = "multipart/form-data"}))
{
@Html.AntiForgeryToken()
<input type="file" name="files"><br>
<input type="submit" value="Upload File to Server">
}
Controller 控制者
[HttpPost]
[ValidateAntiForgeryToken]
public void YourAction(IEnumerable<HttpPostedFileBase> files)
{
if (files != null)
{
foreach (var file in files)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(file.FileName);
// TODO: need to define destination
var path = Path.Combine(Server.MapPath("~/Upload"), fileName);
file.SaveAs(path);
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.