上传图像并获取其字节

时间:2009-12-19 22:21:07

标签: c# .net asp.net-mvc file-upload

我有这样的表格

<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>

如何在Controller中获取图像字节?

3 个答案:

答案 0 :(得分: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
      }

答案 1 :(得分:2)

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

答案 2 :(得分: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.
}

对不起我误解了问题是什么。