无法将类型为“System.Web.HttpInputStream”的对象强制转换为“System.IO.FileStream”MVC 3

我遇到了关于从HttpInputStream到FileStream的转换类型的问题。

我怎么做的?

我有一个HttpPostedFileBase对象,我想拥有FileStream。

我写:

 public void Test(HttpPostedFileBase postedFile) { FileStream fileStream = (FileStream)(postedFile.InputStream); // throw exception FileStream anotherFileStream = postedFile.InputStream as FileStream; // null } 

我也试过了

 public void Test(HttpPostedFileBase postedFile) { Stream stream = postedFile.InputStream as Stream; FileStream myFile = (FileStream)stream; } 

但没有成功。

为什么在postedFile.InputStream出现HttpInputStream类型?

我怎么能解决这个问题呢?

谢谢

从HTTP调用获得的流是只读的顺序(不可搜索),FileStream是可读/写的。 首先需要将HTTP调用中的整个流读入字节数组,然后从该数组中创建FileStream。

 public byte[] LoadUploadedFile(HttpPostedFileBase uploadedFile) { var buf = new byte[uploadedFile.InputStream.Length]; uploadedFile.InputStream.Read(buf, 0, (int)uploadedFile.InputStream.Length); return buf; } 

我使用了以下内容,它在同样的情况下工作得很好

 MemoryStream streamIWant = new MemoryStream(); using (Stream mystream = (Stream)AmazonS3Service.GetObjectStream(AWSAlbumBucketName, ObjectId)) { mystream.CopyTo(streamIWant); } return streamIWant; 

GetObjectStream返回问题中提到的相同类型的字符串。

您可以使用.SaveAs方法来保存文件内容。 HttpInputSteam可能是因为它是通过http [浏览器]上传的

  postedFile.SaveAs("Full Path to file name"); 

您也可以使用CopyTo

 FileStream f = new FileStream(fullPath, FileMode.CreateNew); postedFile.InputStream.CopyTo(f); f.Close(); 

下面的代码对我有用..

使用BinaryReader对象从流中返回字节数组,如:

 byte[] fileData = null; using (var binaryReader = new BinaryReader(Request.Files[0].InputStream)) { fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength); } 

如何从HttpPostedFile创建字节数组