2016-02-22 30 views
1

我是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和其他屬性),但文件未上傳。
另一種嘗試將它們保存在服務器上的方法具有相同的結果。
請幫忙。我在這個問題上掙扎了一個多星期。
謝謝。

+0

您的方法UploadDoc中有任何異常嗎? – AdrienTorris

+0

不,沒有例外。該應用程序運行,但該文件未上傳。謝謝您的回答。 –

+0

執行行文件時會發生什麼.SaveAs(路徑)?它工作嗎?路徑是否正確?你的代碼看起來很棒,你必須在某處出現異常。 – AdrienTorris

回答

0
Controller 

[HttpPost] 
     public ActionResult Save(List<HttpPostedFileBase> fileUpload, TicketSystemAPI.Models.Tickets.Ticketss ticket) 
     { 

      if (!Helper.Common.LogedInUser()) 
       return RedirectToAction("Login", "Logins"); 

      List<string> myTempPaths = new List<string>(); 

      if (fileUpload.Count > 1) 
      { 


       foreach (var file in fileUpload) 
       { 
        if (file != null && file.ContentLength > 0) 
        { 

         int MaxContentLength = 1024 * 1024 * 3; //3 MB 
         string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png" }; 
         if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.')))) 
         { 
          ModelState.AddModelError("File", "Please file of type: " + string.Join(", ", AllowedFileExtensions)); 
          TempData["error"] = ("Please file of type: " + string.Join(", ", AllowedFileExtensions)); 

          // return ("TicketsEdit",TempData["error"].ToString()); 
         } 
         else if (file.ContentLength > MaxContentLength) 
         { 
          ModelState.AddModelError("File", "Your file is too large, maximum allowed size is: " + MaxContentLength + " MB"); 
         } 
         else 
         { 
          string extension = Path.GetExtension(file.FileName); 
          string fileName = DateTime.Now.ToString("ddMMyyHHmmss").ToString() + extension; 
          //   TempData["FileName"] = fileName; 


          //var filename = Guid.NewGuid() + Path.GetFileName(file.FileName); 
          //file.SaveAs(Path.Combine(Server.MapPath("~/Attach/Document"), Guid.NewGuid() + Path.GetExtension(file.FileName))); 
          file.SaveAs(Path.Combine(Server.MapPath("~/Attach/Document"), fileName + Path.GetExtension(file.FileName))); 
          ModelState.Clear(); 
          //  ViewBag.Message = "File uploaded successfully"; 
          myTempPaths.Add(fileName); 
         } 
        } 
       } 
      } 



View 


@using (Html.BeginForm("Save", "Tickets", 
FormMethod.Post, new { enctype = "multipart/form-data", id = "frmID" })) 
{ 
    @Html.HiddenFor(i => i.FileName) 

    <div class="labelstyle"> 
     <label>Files</label> 
    </div> 

    <div id="uploaders"> 
     <input type="file" id="fileToUpload" 
       name="fileUpload" multiple="multiple" style="float: left;" /> 
     <br /> 
     <span id="spnFile" style="float: left; color: #FF0000"></span> 
     @Html.ValidationMessage("File") 
     @Html.Hidden("hdnFileUpload") 
    </div> 
    <br /> 
    <div class="col-lg-6"> 
     <button class="btn btn-primary" id="btnAddIssue" type="submit">Submit</button> 
    </div> 
    <br /> 
    <div class="control-section" style="padding: 0px;"> 
     <div id="selectedFiles"></div> 
    </div> 
} 
+0

謝謝你的回答,Jeb。我試過你的代碼,我得到錯誤「對象引用未設置爲對象的實例。」在if(fileUpload.C​​ount> 1)。你只能從視圖中調用Save()方法,或者你也可以通過另一種方法(如Create())從控制器調用它? –