我正在开发一个 Windows Phone 应用程序。这个应用程序将允许用户拍照并上传到我的服务器。我已经成功实现了这个功能。然而,我注意到有时候图片上传不完整。我怀疑这是因为有人在上传完成之前让应用程序休眠了,或者连接中断了。我真的不知道如何解决这个问题。我在这里放置了我的代码。希望有人能提供一些见解。
Client Side - Windows Phone App - Picture.cs
--------------------------------------------
public event EventHandler Upload_Succeeded;
public event EventHandler Upload_Failed;
public void Upload()
{
try {
WebRequest request = HttpWebRequest.Create(GetBackendPictureUploadUrl());
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetRequestStream(new AsyncCallback(UploadBeginGetRequestStreamCallBack), request);
} catch (Exception ex)
{
Upload_Failed(this, EventArgs.Empty);
}
}
private void UploadBeginGetRequestStreamCallBack(IAsyncResult ar)
{
try {
StringBuilder sb = new StringBuilder();
this.ImageBytes.ToList<byte>().ForEach(x => sb.AppendFormat("{0}.", Convert.ToUInt32(x)));
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("username", GetUsername());
parameters.Add("pictureByts", sb.ToString());
string data = string.Empty;
foreach (string key in parameters.Keys)
{
data += key;
data += "=";
data += parameters[key];
data += "&";
}
data = data.Substring(0, data.Length - 1);
HttpWebRequest webRequest = (HttpWebRequest)(ar.AsyncState);
using (Stream postStream = webRequest.EndGetRequestStream(ar))
{
byte[] byteArray = Encoding.UTF8.GetBytes(data);
postStream.Write(byteArray, 0, byteArray.Length);
postStream.Close();
}
webRequest.BeginGetResponse(new AsyncCallback(Upload_Completed), webRequest);
} catch (Exception ex)
{
Upload_Failed(this, EventArgs.Empty);
}
}
private void Upload_Completed(IAsyncResult result)
{
Upload_Succeeded(this, EventArgs.Empty);
}
Server Size - ASP.NET MVC - MyController.cs
-------------------------------------------
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddPicture(string username, string pictureBytes)
{
string path = ConfigurationManager.AppSettings["pictureDirectory"] + "/" + username + "/";
if (Directory.Exists(path) == false)
Directory.CreateDirectory(path);
string filePath = path + "/" + Guid.NewGuid().ToString() + ".png";
// Save the picture to the file system
string[] bytesToConvert = pictureBytes.Split('.');
List<byte> fileBytes = new List<byte>();
bytesToConvert.ToList<string>().Where(x => !string.IsNullOrEmpty(x)).ToList<string>().ForEach(x => fileBytes.Add(Convert.ToByte(x)));
using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
{
byte[] bytes = fileBytes.ToArray();
fileStream.Write(bytes, 0, bytes.Length);
fileStream.Close();
}
}
我很困惑,这段代码在我看来是正确的。但我注意到服务器上正在写入文件。有时它们只是灰色图像。有时看起来只写了图像的一部分而不是全部。我做错了什么?如何确保文件完全上传/写入?肯定有某种方法可以解决这个问题,Facebook等显然已经做到了。我做错了什么?