2016-08-23 41 views
3

如何使用c#將byte []轉換爲HttpPostedFileBase。在這裏我嘗試了以下方法。如何使用c#將字節[]轉換爲HttpPostedFileBase#

byte[] bytes = System.IO.File.ReadAllBytes(localPath); 
HttpPostedFileBase objFile = (HttpPostedFileBase)bytes; 

我得到一個不能隱式轉換錯誤。

+2

的可能的複製http://stackoverflow.com/questions/28179730/is-it-possible-to-convert-byte- to-httppostedfile –

回答

10

創建自定義發佈文件怎麼樣? :)

public class MemoryPostedFile : HttpPostedFileBase 
{ 
    private readonly byte[] fileBytes; 

    public MemoryPostedFile(byte[] fileBytes, string fileName = null) 
    { 
     this.fileBytes = fileBytes; 
     this.FileName = fileName; 
     this.InputStream = new MemoryStream(fileBytes); 
    } 

    public override int ContentLength => fileBytes.Length; 

    public override string FileName { get; } 

    public override Stream InputStream { get; } 
} 

,你可以簡單地使用這樣的:

byte[] bytes = System.IO.File.ReadAllBytes(localPath); 
HttpPostedFileBase objFile = (HttpPostedFileBase)new MemoryPostedFile(bytes); 
+0

'private Stream inputStream'行不需要,也沒有使用。我試圖編輯答案,但我發現[我們不應該編輯其他代碼](http://meta.stackoverflow.com/a/276580/4826084)。 – Oskar

+0

@Oskar你完全正確(關於不必要的inputStream字段)當我寫答案時,我完全錯過了。我會相應更新。謝謝你指出。 –

+0

我在下面的代碼中編譯時遇到了下面的錯誤:Line:public override int ContentLength => fileBytes.Length;錯誤:fileBytes是一個字段,但像使用類型一樣使用。請幫我解決@KarlPatrikJohansson – Ronak