简体   繁体   English

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

[英]Ensuring File Upload from Windows Phone to ASP.NET MVC 3

I am working on a Windows Phone app. 我正在开发Windows Phone应用程序。 This app will let users take pictures and upload them to my server. 这个应用程序将让用户拍照并上传到我的服务器。 I have successfully implemented this. 我已经成功实现了这个。 However, I've noticed that sometimes the picture does not get uploaded properly. 但是,我注意到有时图片无法正确上传。 I suspect this happens when someone puts the app to sleep before its done uploading. 我怀疑当有人在完成上传之前让应用程序进入睡眠状态时会发生这种情况。 Or the connectivity gets interrupted. 或者连接中断。 I'm really not sure how to do address this. 我真的不知道如何解决这个问题。 I've included my code here. 我在这里包含了我的代码。 I'm hoping someone can provide some insight. 我希望有人可以提供一些见解。

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();
  }
}

I'm so confused. 我很混乱。 This code looks right in my opinion. 在我看来,这段代码看起来正确。 But I've noticed that files are being written on my server. 但我注意到文件正在我的服务器上写入。 Sometimes they are just grey images. 有时它们只是灰色图像。 Sometimes it looks like part of the image was written but not the whole thing. 有时看起来图像的一部分是写的而不是整个。 What am I doing wrong? 我究竟做错了什么? How do I ensure that the file is completely uploaded / written properly? 如何确保文件完全上载/写入正确? There has to be some way of doing this. 必须有一些方法来做到这一点。 Clearly Facebook etc. are doing this. 显然Facebook等正在这样做。 What am I doing wrong? 我究竟做错了什么?

You need to set ContentLength in your Upload method. 您需要在Upload方法中设置ContentLength。 To do that, you should compute your finished data buffer before you make the async request. 为此,您应该在进行异步请求之前计算已完成的数据缓冲区。 Then you will have the length you need (after UTF8 encode). 然后你将获得所需的长度(在UTF8编码之后)。 Then supply the data to the stream when the callback occurs. 然后在回调发生时将数据提供给流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM