我有同样的问题
@using (Html.BeginForm("CreateRequest", "SupportRequest", FormMethod.Post, new { id = "frmStemplate", enctype = "multipart/form-data" }))
{
<td><input type="file" name="FirstFile" id="FirstFile" class="button" />
<input type="button" class="button" id="FirstFileupload" value="upload" onclick="Javascript:DocumentUpload();"/>
}
<script language="javascript" type="text/javascript">
function DocumentUpload()
{
var BrowseFile = $('#FirstFile').val();
if (BrowseFile != null && BrowseFile != "") {
alert(BrowseFile);
$.ajax({
type: 'POST',
dataType: 'json',
url: '@Url.Content("~/SupportRequest/UploadFiles")?fileElementId=' + BrowseFile,
success: function (data) {
alert('Hi'); //debugger;
if (data.Result == "SUCCESS") {
alert('Hi');
}
else {
ShowInfo('Document Uploaded Successfully');
}
}
});
}
}
</script>
在控制器方面,我有:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadFiles(string fileElementId, FormCollection formColl)
{
var FirstFile = Request.Files;
foreach (string upload in Request.Files)
{
if (!Request.Files[upload].HasFile()) continue;
string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/";
string filename = Path.GetFileName(Request.Files[upload].FileName);
Request.Files[upload].SaveAs(Path.Combine(path, filename));
}
return Json(new { Filename = "" });
}
但我的Request.Files
始终是null
。
我尝试了几件事,比如将代码更改为Request.Files["FirstFile"]
等。每次,文件集都是空的。
答案 0 :(得分:2)
您需要在控制器操作参数中使用HttpPostedFileBase
才能获取已发布的filedata。
请阅读Phil Haack的全部article
答案 1 :(得分:0)
由于您要创建数据的帖子,因此您需要发布文件数据。看到这篇文章:
答案 2 :(得分:0)
我使用可以轻松上传文件的表单集合做了不同的方式。就像你在cshtml页面中的开始表单中添加该行一样。
public ActionResult Create([Bind(Include="Id,Name,Pic,ActiveStatus")] FormCollection form)
{
string Pic = "";
var file = Request.Files[0];
if (file.ContentLength > 0)
{
Pic = string.Format("~/Uploads/Category/{0}", file.FileName);
file.SaveAs(HttpContext.Server.MapPath(Pic));
}
ItemCategory obj = new ItemCategory
{
Name = form["Name"].ToString(),
Pic = file.FileName
};
db.ItemCategories.Add(obj);
db.SaveChanges();
return RedirectToAction("Index");