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 等正在这样做。我究竟做错了什么?

4

1 回答 1

0

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

于 2012-07-24T20:58:16.103 回答