Javascript HttpPostedfileBase 使用 jQuery Ajax 为空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28373894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HttpPostedfileBase is null using jQuery Ajax
提问by salar
I have problem with uploading file In Asp.net Mvc. First of all I should use Ajax to pass the upload file value.
我在 Asp.net Mvc 中上传文件时遇到问题。首先我应该使用 Ajax 来传递上传文件的值。
In javascript I have model that I fill it, When I check it with debugger is correctly fill the object, but when I send this model to server (Controller )
在javascript中,我有填充它的模型,当我用调试器检查它时是否正确填充了对象,但是当我将此模型发送到服务器(Controller)时
The httpPostedfileBase value is Always null.
httpPostedfileBase 值始终为空。
I search it on google, in some post I saw that I cant use file uploader with Ajax, but in other I saw that I can.
我在谷歌上搜索它,在一些帖子中我看到我不能在 Ajax 中使用文件上传器,但在其他帖子中我看到我可以。
But I can not fix my Code.
但我无法修复我的代码。
There is my Javascript Code.
有我的 Javascript 代码。
$(document).ready(function () {
$('#btnUploadFile').on('click', function () {
var data= new FormData();
debugger;
var files = $("#fileUpload").get(0).files;
if (files.length > 0) {
data.append("UploadedImage", files[0]);
}
var ResturantSharingViewModel =
{
Type: $("#SharingTargetType").val(),
SharingTitle: $("#SharingTitle").val(),
content: $("#Content").val(),
ItemId : $("#ItemId").val(),
Photos: files[0]
};
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: '<%= Url.Action("SaveOneDatabase")%>',
data: JSON.stringify(ResturantSharingViewModel),
success: function (result) {
var rs = result;
},
error: function () {
alert("Error loading data! Please try again.");
}
});
My Controller public virtual bool SaveOneDatabase(ResturantSharingViewModel result)
My ResturantSharingViewModel View Model
我的控制器public virtual bool SaveOneDatabase(ResturantSharingViewModel result)
我的 ResturantSharingViewModel 视图模型
public class ResturantSharingViewModel
{
public Guid SharingPremiumHistoryID { get; set; }
public string SharingTitle { get; set; }
public string Content { get; set; }
public DateTime AddedDate { get; set; }
public bool IsSubmit { get; set; }
public DateTime SubmitedDate { get; set; }
public IEnumerable<SelectListItem> SharingTypes { get; set; }
public IEnumerable<SelectListItem> SharingTargetType { get; set; }
public short Type { get; set; }
public Guid ItemId { get; set; }
public HttpPostedFileBase[] Photos { get; set; }
}
My Html Elements
我的 HTML 元素
<form enctype="multipart/form-data">
<article>
<%--<% =Html.BeginForm("Add","PremiumSharing") %>--%>
<hgroup class="radiogroup">
<h1>????? ???</h1>
<%= Html.HiddenFor(model => model.SharingPremiumHistoryID) %>
<%= Html.HiddenFor(model => model.ItemId) %>
<div class="group">
<span> ????? ?? </span>
<%= Html.DropDownListFor(model => model.SharingTargetType, Model.SharingTypes) %>
</div>
</hgroup>
<div class="newseditor">
<div class="input-form">
<%= Html.LabelFor(model => model.SharingTitle, "????? ???") %>
<%= Html.TextBoxFor(model => model.SharingTitle) %>
</div>
<div class="input-form">
<%= Html.LabelFor(model => model.Content, "??? ???") %>
<%= Html.TextAreaFor(model => model.Content) %>
</div>
<div><input id="fileUpload" type="file" />
</div>
<% if (ViewBag.IsInEditMode != null && !(bool)ViewBag.IsInEditMode)
{%>
<div class="input-form">
<%= Html.CheckBox("SendToInTheCity") %> ????? ?? ??? ??? ???? ???????
</div>
<%} %>
<div class="input-submit">
<button name="post" id="btnUploadFile" onclick="uploadFile()" >????? ???</button>
</div>
<br />
</div>
采纳答案by Andreas
First, it's possible to upload with Ajax, the important thing is you need to set <form enctype="multipart/form-data"></form>on you form to tell it your form has an file upload input. Then you need to accept HttpPostedFileBaseas an input parameter in your controller action.
首先,可以使用 Ajax 上传,重要的是您需要<form enctype="multipart/form-data"></form>在表单上设置以告诉它您的表单有一个文件上传输入。然后,您需要HttpPostedFileBase在控制器操作中接受作为输入参数。
Try this. Example of jquery upload code. (Taken mostly from How can I upload files asynchronously?)
尝试这个。jquery 上传代码示例。(主要来自如何异步上传文件?)
function uploadFile(uploadId) {
var formData = new FormData($('form')[0]);
$.ajax({
url: '<%= Url.Action("SaveOneDatabase")%>',
type: 'Post',
beforeSend: function(){},
success: function(result){
},
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload) { // Check if upload property exists
// Progress code if you want
}
return myXhr;
},
error: function(){},
data: formData,
cache: false,
contentType: false,
processData: false
});
}
HTML Form needs this attribute. See this post why you need it -> What does enctype='multipart/form-data' mean?
HTML 表单需要这个属性。看到这篇文章你为什么需要它 -> enctype='multipart/form-data' 是什么意思?
enctype="multipart/form-data"
C#
C#
[HttpPost]
public ActionResult SaveOneDatabase(HttpPostedFileBase file)
{
}
回答by a moradi
View:
看法:
<script/>
var add_photo_url = "@Url.Action("AddPhoto", "Gallery")";
var model = new FormData();
var i=0;//selected file index
model.append("File", files[i]);
model.append("Name", "test");
$.ajax({// and other parameter is set here
url: add_photo_url,
type: "POST",
data: model,
dataType: "json",
cache: false,
contentType: false,
processData: false
})
.always(function (result) {
});
</script>
View Model:
查看型号:
public class PhotoAlbumViewModel {
public string Name { get; set; }
public HttpPostedFileBase File { get; set; }
}
Controller:
控制器:
public JsonResult AddPhoto(PhotoAlbumViewModel model) {
// var result =...
// and set your result;
return Json(result, JsonRequestBehavior.AllowGet);
}
回答by Pratap Singh Mehra
I have modified @a moradi's answer.
我修改了@a moradi 的答案。
JS:
JS:
//FormData:
//Treat it like a normal form but with "multipart/form-data" encoding type.
//Inside it works on same XMLHttpRequest.send() method.
var model = new FormData();
model.append("File", $('#file')[0].files[0]);
model.append("Name", "Name");
$.ajax({
url: someUrl,
type: "POST",
data: model,
//contentType:
//Sets the ContentType in header.
//The default contentType is "application/x-www-form-urlencoded; charset=UTF-8". But this will prevent us sending AntiForgeryToken to service/controller.
//To prevent this contentType is set to false.
contentType: false,
//processData:
//To prevent data in data option getting converted to string format, 'processData' option is set to false.
processData: false,
success = function (m) {...}
error = function (m) {...}
});
View Model:
查看型号:
public class PhotoAlbumViewModel {
public string Name { get; set; }
public HttpPostedFileBase File { get; set; }
}
Controller:
控制器:
public JsonResult AddPhoto(PhotoAlbumViewModel model) {
...
}
Refrence:
参考:
Reffer following links for details: FormData, JQuery, ContentType
有关详细信息,请参阅以下链接:FormData、JQuery、ContentType

