我是C#和ASP.NET MVC的新手。
我想上傳文件,並能夠根據它們的依賴下載它們,在Visual Studio 2013年
我有代表團型號:在MVC中上傳和下載文件5
public int idDelegation { get; set; }
public string Delegation_Name { get; set; }
public string Employee_Name { get; set; }
public virtual ICollection<Doc> Doc { get; set; }
和文檔模型:
public int idDoc { get; set; }
public int idDelegation { get; set; }
public string Doc_Name { get; set; }
public DateTime Doc_Validity_Date { get; set; }
public byte[] Content { get; set; }
public virtual Delegation Delegation { get; set; }
我想要做的是上傳與它相關的委託相關的文檔。
所以我嘗試過不同的方式來做到這一點,包括將它們保存到服務器或數據庫。
試圖將它們保存在數據庫中,我創建的DocsController方法UploadDoc():
[HttpPost]
public ActionResult UploadDoc(HttpPostedFileBase file)
{
string path = Server.MapPath(@"LocalPath\" + file.FileName);
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath(path), fileName);
file.SaveAs(path);
}
byte[] uploadedFile = new byte[viewModelDoc.file.InputStream.Length];
viewModelDoc.file.InputStream.Read(uploadedFile, 0, uploadedFile.Length);
return RedirectToAction("Index");
}
,我把它稱爲在HttpPost在DocsController創建方法:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "idDoc,idDoc_Type,idDelegation,Doc_Name,Doc_Validity_Date, Content, FileMimeType")] Doc doc, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
UploadDoc(doc, file);
db.Doc.Add(doc);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.idDelegation = new SelectList(db.Delegation, "idDelegation", "Delegation_Name", doc.idDelegation);
ViewBag.idDoc_Type = new SelectList(db.Doc_Type, "idDoc_Type", "Doc_Type_Name", doc.idDoc_Type);
return View(doc);
}
我創建的視圖模型UploadDoc:
public class UploadDoc
{
public int idDoc { get; set; }
public string Doc_Name { get; set; }
public DateTime Doc_Validity_Date { get; set; }
public byte[] Content { get; set; }
public virtual Delegation Delegation { get; set; }
public HttpPostedFileBase file { get; set; }
}
然後,在我的Create.cshtml查看:
<div class="form-group">
I
@using (Html.BeginForm("UploadDoc", "Docs",
FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<div class="col-md-10">
@Html.TextBoxFor(x => x.file, new { type = "file" })
@Html.ValidationMessageFor(x=>x.file)
<button type="submit"> Upload </button>
</div>
}
</div>
不幸的是,應用程序創建關於數據庫中文檔(文件)的條目(如Doc_Name和其他屬性),但文件未上傳。
另一種嘗試將它們保存在服務器上的方法具有相同的結果。
請幫忙。我在這個問題上掙扎了一個多星期。
謝謝。
您的方法UploadDoc中有任何異常嗎? – AdrienTorris
不,沒有例外。該應用程序運行,但該文件未上傳。謝謝您的回答。 –
執行行文件時會發生什麼.SaveAs(路徑)?它工作嗎?路徑是否正確?你的代碼看起來很棒,你必須在某處出現異常。 – AdrienTorris