2013-04-16 230 views
44

我使用文件上傳選項上傳文件。而我直接查看發送此文件中POST方法等來控制,ASP.Net MVC - 從HttpPostedFileBase中讀取文件而不保存

[HttpPost] 
    public ActionResult Page2(FormCollection objCollection) 
    { 
     HttpPostedFileBase file = Request.Files[0]; 
    } 

假設,我上傳一個記事本文件。如何讀取此文件&將此文本追加到字符串生成器,,而不保存該文件....

我知道關於這個文件,我們可以讀取這個文件。但是,如何在不保存的情況下從HttpPostedFileBase讀取此文件?

回答

62

這可以通過使用httpPostedFileBase類完成返回HttpInputStreamObject按規定here

您應該流轉換爲字節數組,然後你可以閱讀文件內容

請參考以下鏈接

http://msdn.microsoft.com/en-us/library/system.web.httprequest.inputstream.aspx]

希望這有助於

UPDATE:

您從HTTP調用得到的流是隻讀的順序 (非可搜索),並因此FileStream讀/寫可查找。您需要首先將來自HTTP調用的整個流讀取到字節 數組中,然後從該數組創建FileStream。

here

// Read bytes from http input stream 
BinaryReader b = new BinaryReader(file.InputStream); 
byte[] binData = b.ReadBytes(file.ContentLength); 

string result = System.Text.Encoding.UTF8.GetString(binData); 
+1

http://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers –

+4

附: b.ReadBytes()需要一個int,但file.InputStream.Length是一個很長的 –

+2

,但file.InputStream.ContentLength是一個int –

34

截取的替代方法是使用的StreamReader。

public void FunctionName(HttpPostedFileBase file) 
{ 
    string result = new StreamReader(file.InputStream).ReadToEnd(); 
} 
+0

這將清空流製作file.Length = 0 – PUG

+3

同意,但在很多情況下,這是確定的。 –

+2

雖然+1,你沒有處置'IDisposable'。 –

5

的輕微變化Thangamani任職Palanisamy答案,它允許將被設置在二進制讀取和修正輸入長度問題在他的評論。

string result = string.Empty; 

using (BinaryReader b = new BinaryReader(file.InputStream)) 
{ 
    byte[] binData = b.ReadBytes(file.ContentLength); 
    result = System.Text.Encoding.UTF8.GetString(binData); 
} 
相關問題