[英]MVC upload and save form image with Ajax
我有一個帶有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" />
}
現在,我想使用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;
});
在我的控制器文件中。
public ActionResult Save(UserProfileSettings settings)
{
var image = setings.Image
var name = settings.Firstname
}
我的模特
public class UserProfileSettings
{
public string FirstName { get; set; }
public HttpPostedFileBase Image { get; set; }
}
問題是在我的控制器方法中,我正在獲取settins.FirstName,但是settings.Image始終為null。 我認為,使用這種方法無法序列化圖像文件。
嘗試使用jquery插件進行多重上傳: http ://blueimp.github.io/jQuery-File-Upload/
正如Darin Dimitrov之前建議的那樣 ,最好使用jquery表單插件 。 我在另一個答案已經張貼了這個位置 。
快速范例
視圖
@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">
}
控制者
[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.