2009-09-30 46 views
1

在C#中,而不是必须使用httpwebrequest从web下载文件,将其保存到文件的某处,然后使用POST将文件上传到webservice作为参数之一...我可以使用流文件作为源使用网络文件将文件上传到Web API吗?

我可以改为以某种方式从httpwebresponse打开一个阅读器流,然后将其流入http POST?任何代码有人可以张贴来显示如何?

换句话说,我试图避免首先保存到磁盘。

感谢

回答

2

类似的东西应该做的伎俩:

HttpWebRequest downloadRequest = WebRequest.Create(downloadUri) as HttpWebRequest; 
using(HttpWebResponse downloadResponse = downloadRequest.GetResponse() as HttpWebResponse) 
{ 
    HttpWebRequest uploadRequest = new HttpWebRequest(uploadUri); 
    uploadRequest.Method = "POST"; 
    uploadRequest.ContentLength = downloadResponse.ContentLength; 
    using (Stream downloadStream = downloadResponse.GetResponseStream()) 
    using (Stream uploadStream = uploadRequest.GetRequestStream()) 
    { 
     byte[] buffer = new byte[4096]; 
     int totalBytes = 0; 
     while(totalBytes < downloadResponse.ContentLength) 
     { 
      int nBytes = downloadStream.Read(buffer, 0, buffer.Length); 
      uploadStream.Write(buffer, 0, nBytes); 
      totalBytes += nRead; 
     } 
    } 
    HttpWebResponse uploadResponse = uploadRequest.GetResponse() as HttpWebResponse; 
    uploadResponse.Close(); 
} 

(未测试的代码)

+0

哇...我会尝试一下,当我回到家里,然后更新...非常感谢 – Greg 2009-09-30 23:37:10

+0

嘿托马斯 - 回到这个 - 我注意到我有一个问题,如果我的目标是服务器不提供ContentLength(例如在downloadResponse.ContentLength)的页面。我似乎得到“System.NotSupportedException:此流不支持查找操作..”。这里的任何想法如何解决这个问题? – Greg 2009-12-08 07:13:46

+0

你在哪个指令中得到这个异常? – 2009-12-08 09:37:27

相关问题