【发布时间】:2012-05-18 04:31:08
【问题描述】:
我以为我找到了一种通过使用 WebClient.UploadFile 而不是 HttpWebRequest 来简化代码的方法,但我最终在服务器端得到了一个文件,该文件太短了几十个字节并且损坏。知道错误在哪里吗?
谢谢
使用 HttpWebRequest(工作正常):
HttpWebRequest req = (HttpWebRequest)HttpWebRequest
.Create("http://" +
ConnectionManager.FileServerAddress + ":" +
ConnectionManager.FileServerPort +
"/binary/up/" + category + "/" +
Path.GetFileName(filename) + "/" + safehash);
req.Method = "POST";
req.ContentType = "binary/octet-stream";
req.AllowWriteStreamBuffering = false;
req.ContentLength = bytes.Length;
Stream reqStream = req.GetRequestStream();
int offset = 0;
while (offset < ____)
{
reqStream.Write(bytes, offset, _________);
_______
_______
_______
}
reqStream.Close();
try
{
HttpWebResponse resp = (HttpWebResponse) req.GetResponse();
}
catch (Exception e)
{
_____________
}
return safehash;
使用 WebClient(服务器端损坏的文件):
var client = new WebClient();
client.Encoding = Encoding.UTF8;
client.Headers.Add(HttpRequestHeader.ContentType, "binary/octet-stream");
client.UploadFile(new Uri("http://" +
ConnectionManager.FileServerAddress + ":" +
ConnectionManager.FileServerPort +
"/binary/up/" + category + "/" +
Path.GetFileName(filename) + "/" + safehash), filename);
return safehash;
服务器端是一个 WCF 服务:
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "up/file/{fileName}/{hash}")]
void FileUpload(string fileName, string hash, Stream fileStream);
【问题讨论】:
-
如果您的目标是 WCF 服务,您是否有理由不将其作为服务使用,而是尝试手动向其发布数据?我们在这里谈论上传什么样的文件大小? WCF 有一些非常小的默认文件大小限制。
WebClient实现是否存在保活或超时问题?你有任何例外吗? -
如果您在 Fiddler 等工具中查看请求,是否显示出两者之间的任何差异?
-
提琴手.. 嗯嗯好主意。我现在会检查。 Cory:两端都没有问题,只是文件损坏。
标签: wcf file-upload httpwebrequest webclient