【发布时间】:2012-08-10 12:54:40
【问题描述】:
任何人都可以帮助解决我遇到的一个小问题,我有 WCF Rest Based Service,它具有可以接受流的功能,这将用于将图像/音频/视频上传到服务器,然后将它们存储在某处的服务器。
测试和图像,它似乎工作,我在客户端中选择图像,几秒钟后图像出现在服务器上预期的位置,但是当我尝试在 Windows 图片查看器中打开图像时(或任何图像查看器),我得到“没有可用的预览”,并且没有要查看的图像。
我假设这是因为我没有从流中正确地重新创建文件。
这是 WCF Rest Service 上的方法
public void PutFileInFolder(int eid, Stream fileContents)
{
try
{
byte[] buffer = new byte[32768];
MemoryStream ms = new MemoryStream();
int bytesRead = 0;
int totalBytesRead = 0;
do
{
bytesRead = fileContents.Read(buffer, 0, buffer.Length);
totalBytesRead += bytesRead;
ms.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
//now have file in memorystream
//save the file to the users folder
FileStream file = new FileStream(@"C:\bd_sites\ttgme\wwwroot\Evidence\{" + ed.LearnerID + @"}\" + ed.EvidenceFileName, FileMode.Create, System.IO.FileAccess.Write);
byte[] bytes = new byte[ms.Length];
ms.Read(bytes, 0, (int)ms.Length);
file.Write(bytes, 0, bytes.Length);
file.Close();
ms.Close();
}
catch (Exception ex)
{
return;
}
}
这是发送文件/图像的客户端函数
private void PostFile(EvidenceObject eo)
{
try
{
// Create the REST request.
string url = ConfigurationManager.AppSettings["serviceUrl"];
string requestUrl = string.Format("{0}/PutFileInFolder/{0}", 1001);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
request.Method = "POST";
request.ContentType = "text/plain";
byte[] fileToSend = File.ReadAllBytes(txtFileName.Text);
request.ContentLength = fileToSend.Length;
using (Stream requestStream = request.GetRequestStream())
{
// Send the file as body request.
requestStream.Write(fileToSend, 0, fileToSend.Length);
requestStream.Close();
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
Console.WriteLine("HTTP/{0} {1} {2}", response.ProtocolVersion, (int)response.StatusCode, response.StatusDescription);
MessageBox.Show("File sucessfully uploaded.", "Upload", MessageBoxButton.OK, MessageBoxImage.Information);
this.DialogResult = true;
}
catch (Exception ex)
{
MessageBox.Show("Error during file upload: " + ex.Message, "Upload", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
也刚刚测试了一个视频文件,原来的文件播放的很好,然后我通过服务上传时,服务器上创建的文件播放不了。
我确信我正在做的事情真的很愚蠢,但任何帮助都非常感谢。
【问题讨论】:
-
忽略这个问题,我自己已经回答过了,但是不让我关闭它。
-
如果您自己解决了,您仍然应该发布自己的答案,以防其他人将来遇到同样的问题。
-
我试过了,但它不允许我发布答案,这就是我留下评论的原因,因为我只能这样做。这与声誉分数和时间限制有关。