2009-12-19 60 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 
     ... 
    }