2014-02-27 19 views
1

其中的FILE表單字段如果我有一個包含多個輸入文件字段(其中'N'是唯一編號)的HTML表單;對於C#Request.Files [n] .FileName

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

然後在C#代碼中;

string inFile = System.IO.Path.GetFileName(Request.Files[M].FileName) 

有沒有什麼方法可以讓我確定「M」的從請求數據的價值,所以我可以匹配針對特定HTML輸入文件類型的字段?

這是在最終用戶可以更新編輯表單上的字段並且對於除文件類型字段以外的所有字段類型都可以正常工作的情況下。

回答

5

所有必要的數據是HttpContext.Request.Files;具體而言,在HttpContext.Request.Files.AllKeys

//HttpContext is a member of `System.Web.Mvc.Controller`, 
//accessible in controllers that inherit from `System.Web.Mvc.Controller`. 
System.Web.HttpFileCollectionBase files = HttpContext.Request.Files; 
string[] fieldNames = files.AllKeys; 
for (int i = 0; i < fieldNames.Length; ++i) 
{ 
    string field = fieldNames[i]; //The 'name' attribute of the html form 
    System.Web.HttpPostedFileBase file = files[i]; 
    string fileName = files[i].FileName; //The path to the file on the client computer 
    int len = files[i].ContentLength; //The length of the file 
    string type = files[i].ContentType; //The file's MIME type 
    System.IO.Stream stream = files[i].InputStream; //The actual file data 
} 
+0

謝謝你,直到你指出「HttpContext.Request」。 Files.AllKeys」 –

0

你可以在服務器端定義一個你自動映射的文件輸入控件。

客戶端:在你的頁面

<input type="file" name="inputFileN" id="inputFileN" runat="server" enctype="multipart/form-data"> 

服務器端:

protected HtmlInputFile inputFileN; 

檢查如何從HtmlInputFile文件內容的文檔:

http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlinputfile.postedfile(v=vs.110).aspx

不完全回答你的問題,但達到目的即

+0

感謝您的想法,但是這是WebForms和我使用MVC。 –

0
<form action="" enctype="multipart/form-data"> 
    Select images: <input type="file" name="inputFileN" multiple> 
    <input type="submit"> 
</form> 

檢索文件:

public void GetFiles() 
{ 
    HttpFileCollection uploadedFiles = Request.Files; 

    for(int i = 0;i < uploadedFiles.Count;i++) { 
      HttpPostedFile userPostedFile = uploadedFiles[i]; 

    if(userPostedFile.ContentLength > 0) { 


    userPostedFile.SaveAs(filepath + "\\" +Path.GetFileName(userPostedFile.FileName)); 
    } 

} 
+0

因此,而不是獲取1個文件,我得到一個文件數組並保存它們? 但我仍然沒有每個文件和它的屏幕形式輸入字段之間的連接/關聯,這就是我所追求的...... –