确保文件从Windows Phone上载到ASP.NET MVC 3



我正在开发一款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等公司正在这么做。我做错了什么?

您需要在Upload方法中设置ContentLength。要做到这一点,您应该在发出异步请求之前计算完成的数据缓冲区。然后你将有你需要的长度(在UTF8编码之后)。然后在回调发生时将数据提供给流。

最新更新