2017-08-13 51 views
1

我正在使用Razor和C#在MS網站上進行文件上傳。ASP.NET Razor文件上傳

如果我有多個文件上傳按鈕,C#代碼如何知道上傳文件來自哪個按鈕?基於文件上傳的按鈕,我將把文件保存到特定的文件夾。

https://docs.microsoft.com/en-us/aspnet/web-pages/overview/data/working-with-files

@using Microsoft.Web.Helpers; 
    @{ 
     var fileName = ""; 
     if (IsPost) { 
      var fileSavePath = ""; 
      var uploadedFile = Request.Files[0]; 
      fileName = Path.GetFileName(uploadedFile.FileName); 
      fileSavePath = Server.MapPath("~/App_Data/UploadedFiles/" + 
       fileName); 
      uploadedFile.SaveAs(fileSavePath); 
     } 
    } 
    <!DOCTYPE html> 
    <html> 
     <head> 
     <title>FileUpload - Single-File Example</title> 
     </head> 
     <body> 
     <h1>FileUpload - Single-File Example</h1> 
     @FileUpload.GetHtml(
      initialNumberOfFiles:1, 
      allowMoreFilesToBeAdded:false, 
      includeFormTag:true, 
      uploadText:"Upload") 
     @if (IsPost) { 
      <span>File uploaded!</span><br/> 
     } 
     </body> 
    </html> 

回答

3

做到這一點的方法是命名的按鈕一樣,但給他們不同的值。然後,您可以執行一個case語句並根據該值指示邏輯。

剃刀

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) 
{ 

    <input type="file" name="FirstUpload" /> 
    <input type="submit" name="submitID" id="submitID" value="Upload1" /> 

    <input type="file" name="SecondUpload" /> 
    <input type="submit" name="submitID" id="submitID" value="Upload2" /> 

} 

控制器

public ActionResult Index() 
     { 
      return View(); 
     } 

     [HttpPost] 
     public ActionResult Index(FormCollection collection) 
     { 
      string btn = Request.Params["submitID"]; 

      switch (btn) 
      { 
       case "Upload1": 

        for (int i = 0; i < Request.Files.Count; i++) 
        { 
         var file = Request.Files[i]; 
        }      
        break; 

       case "Upload2": 

        for (int i = 0; i < Request.Files.Count; i++) 
        { 
         var file = Request.Files[i]; 
        } 
        break; 
      } 

      return View(); 
     } 
0

我也有類似的問題,並結束了與下面的代碼:
剃刀

//BeginForm and other staff 
@foreach (var d in Model.Types) 
{ 
    <input type="file" name="doc:@d.Id:upload" />//@d.Id is the key point 
    <button formenctype="multipart/form-data" 
     type="submit" formaction="/MyController/uploaddoc" 
     name="typeid" formmethod="post" value="@d.Id">//this way I send Id to controller 
     Upload 
    </button> 
} 

MYC的ontroller

[HttpPost] 
[ValidateAntiForgeryToken] 
[Route("mycontroller/uploaddoc")]//same as formaction 
public async Task<ActionResult> UploadDoc(FormCollection data, int typeid) 
{ 
    //restore inpput name 
    var fl = Request.Files["doc:" + typeid.ToString() + ":upload"]; 
    if (fl != null && fl.ContentLength > 0) 
    { 
     var path = Server.MapPath("~/app_data/docs"); 
     var fn = Guid.NewGuid().ToString();//random name 
     using (FileStream fs = System.IO.File.Create(Path.Combine(path, fn))) 
     { 
      await fl.InputStream.CopyToAsync(fs); 
     } 
    } 

}