2009-12-19 64 views
1

我有這樣一個形式上傳圖片,並得到其字節

<form name="" method="post" action="Save" enctype="multipart/form-data"> 
     <div id="dialog" title="Upload files">   
     <input type="file" id="Image" name="fileUpload" size="23"/> 
     </div> 
     <input type="submit" value="Create" /> 
</form> 

我如何得到前人的精力在控制器中獲得的圖像字節?

回答

11

將以下內容添加到您的控制器方法中。

 var file = Request.Files["Image"]; 
     if (file != null) 
     { 
     byte[] fileBytes = new byte[file.ContentLength]; 
     file.InputStream.Read(fileBytes, 0, file.ContentLength); 

     // ... now fileBytes[] is filled with the contents of the file. 
     } 
     else 
     { 
     // ... error handling here 
     } 
+2

它應該是 var file = Request.Files [「uploadFile」]; 它將元素名稱作爲索引器 :) – CoffeeCode 2009-12-19 22:51:42

1
HttpFileCollection files; 
InputStream input; 
int loop1; 
string arr1; 

files = Request.Files; 
arr1 = Files.AllKeys; 

for (loop1 = 0; loop1 < arr1.Length; loop1++) { 
    input = files[loop1].InputStream; 
    // Use input to access the file content. 
} 

對不起;我誤解了問題所在。

+3

這是確定:)
ü忘記定義loop1s類型;) – CoffeeCode 2009-12-19 22:57:29

+0

OK;現在我沒有忘記任何聲明。 :-) – kiamlaluno 2009-12-19 23:10:24

2
foreach (string file in Request.Files) 
    { 
     HttpPostedFileBase hpf = Request.Files[file]; 
     // hpf.ContentLength has the file size in bytes 
     ... 
    }