2016-03-04 92 views
0

好的,所以我正在嘗試向MVC轉移。 我有一個模型,視圖和控制器,但現在我想改變應用程序的創建功能。MVC文件上傳在哪裏可以放置代碼

我正在使用uploads,並且在我的控制器中有這個系統生成的代碼。

Function Create(<Bind(Include:="Id,Course,Category,SubCategory,FileName,FileType,UploadedBy,DateUploaded")> ByVal acAsset As acAsset) As ActionResult 
     If ModelState.IsValid Then 
      db.Assets.Add(acAsset) 
      db.SaveChanges() 
      Return RedirectToAction("Index") 
     End If 
     Return View(acAsset) 
    End Function 

現在我想改變這種做法,它會

  1. 檢查文件夾的存在了課程,分類和子類別。如果此文件夾不存在,則必須創建它。
  2. 通過文件選擇框上傳文件選擇。
  3. 將文件的名稱發佈到數據庫。

代碼不一定是問題,我不知道我應該把控制器放在哪裏?

我已閱讀此article但不處理數據庫文章。

預先感謝您。

回答

1

你只需要添加你的代碼,你想打按鈕控制器點擊

你的剃鬚刀查看代碼

@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, new { enctype = "multipart/form-data" })) 
    { 
     <input type="file" name="file" /> 
     <input type="submit" name="Submit" id="Submit" value="Upload" /> 
    } 

C#代碼

[HttpPost] 
    public ActionResult Upload(HttpPostedFileBase file) 
    { 
     if (file != null && file.ContentLength > 0) 
     { 
      var fileName = Path.GetFileName(file.FileName); 
      var path = Path.Combine(Server.MapPath("~/Images/"), fileName); 
      file.SaveAs(path); 
     } 

     return RedirectToAction("UploadDocument"); 
    } 
} 
0

在你看來

<input type="file" name="file"> 

在控制器

public actionresult(HttpPostedFileBase file) 
{ 
string filename = Path.GetFileName(file.FileName); 
    string contentType = file.ContentType; 
    using (Stream fs = file.InputStream) 
    { 
     using (BinaryReader br = new BinaryReader(fs)) 
     { 
      byte[] bytes = br.ReadBytes((Int32)fs.Length); 
     } 
    } 
//Data Context Code here 
    tableName.File= bytes; 
    db.add(tableName); 
    db.SaveChanges(); 
}