我想用BeginForm()上傳文件到一個文件夾。我創建一個支架項目,我的看法如下所示:文件沒有上傳到目錄
@model Blog.Models.Resource
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm("Create", "Resources", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Resource</h4>
<hr />
@Html.ValidationSummary(true)
<!---Name-->
<div class="form-group">
@Html.LabelFor(model => model.ResourceName, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ResourceName)
@Html.ValidationMessageFor(model => model.ResourceName)
</div>
</div>
<!---Resource-->
<div class="form-group">
@Html.LabelFor(model => model.Item, new { @class = "control-label col-md-2" })
</div>
<input type="file" name="FileUpload1" /><br />
<!---Text-->
<div class="form-group">
@Html.LabelFor(model => model.Text, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextAreaFor(model => model.Text)
@Html.ValidationMessageFor(model => model.Text)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
我的模型如下:
public class Resource
{
[Key]
public int ResourceId { get; set; }
public string ResourceName { get; set; }
public string Item { get; set; }
public string Text { get; set; }
}
我的操作如下:
// GET: /Resources/Create
public ActionResult Create()
{
return View();
}
// POST: /Resources/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Resource resource, HttpPostedFileBase file)
{
//verify file that file exist
if (file != null && file.ContentLength > 0)
{
//get filename
var fileName = Path.GetFileName(file.FileName);
//store file in speficied folder
var path = Path.Combine(Server.MapPath("~/Catalog/Uploads"), fileName);
file.SaveAs(path);
}
if (ModelState.IsValid)
{
db.Resources.Add(resource);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(resource);
}
我一直在尋找在其他帖子周圍,我的情況幾乎如本文所述,但我確實包括{enctype = "multipart/form-data"}
。但是對我來說這是行不通的:
而其他數據保存到文件沒有上傳到指定的文件夾中的數據庫。
任何人都可以幫忙嗎?
它是文件夾權限問題?你有什麼錯誤嗎? – markpsmith
@markpsmith那麼正如Steven和Inanikian所提到的那樣,另外,就像史蒂文所說的那樣,我的編碼類型中有一些空格使得它無用。 – bluetxxth