FileUpload到FileStream

我正在与HttpWebRequest一起发送文件。 我的文件将来自FileUpload UI。 在这里,我需要将文件上传转换为文件流,以便与HttpWebRequest一起发送流。 如何将FileUpload转换为文件流?

由于FileUpload.PostedFile.InputStream给了我Stream,我使用下面的代码将它转换为字节数组

public static byte[] ReadFully(Stream input) { byte[] buffer = new byte[input.Length]; //byte[] buffer = new byte[16 * 1024]; using (MemoryStream ms = new MemoryStream()) { int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } return ms.ToArray(); } } 

可能最好将输入流直接传递给输出流:

 inputStream.CopyTo(outputStream); 

这样,在重新传输之前,您不会将整个文件缓存在内存中。 例如,以下是将其写入FileStream的方法:

 FileUpload fu; // Get the FileUpload object. using (FileStream fs = File.OpenWrite("file.dat")) { fu.PostedFile.InputStream.CopyTo(fs); fs.Flush(); } 

如果您想将其直接写入另一个Web请求,您可以执行以下操作:

 FileUpload fu; // Get the FileUpload object for the current connection here. HttpWebRequest hr; // Set up your outgoing connection here. using (Stream s = hr.GetRequestStream()) { fu.PostedFile.InputStream.CopyTo(s); s.Flush(); } 

这将更有效,因为您将直接将输入文件流式传输到目标主机,而无需先在内存或磁盘上进行缓存。

您无法将FileUpload转换为FileStream。 但是,您可以从FileUpload的PostedFile属性中获取MemoryStream。 然后,您可以使用该MemoryStream来填充您的HttpWebRequest。

您可以使用FileBytes将FileUpload文件直接放入MemoryStream (Tech Jerk的简化答案)

 using (MemoryStream ms = new MemoryStream(FileUpload1.FileBytes)) { //do stuff } 

或者,如果您不需要memoryStream

 byte[] bin = FileUpload1.FileBytes;