通过WebRequest将数据和文件上载到ASP.NET MVC 3操作

时间:2012-06-27 20:09:03

标签: c# asp.net-mvc-3 webrequest

我有一个ASP.NET MVC 3控制器动作。该行动的定义如下:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(string parameter1, HttpPostedFileBase uploadFile)
{
  if (parameter1 == null)
    return Json(new { status = "Error" }, JsonRequestBehavior.AllowGet);

  if (uploadFile.ContentLength == 0)
    return Json(new { status = "Error" }, JsonRequestBehavior.AllowGet);

  return Json(new { status = "Success" }, JsonRequestBehavior.AllowGet);
}

我需要通过C#app上传到此端点。目前,我使用以下内容:

public void Upload()
{
  WebRequest request = HttpWebRequest.Create("http://www.mydomain.com/myendpoint");
  request.Method = "POST";
  request.ContentType = "multipart/form-data";
  request.BeginGetRequestStream(new AsyncCallback(UploadBeginGetRequestStreamCallBack), request);
}

private void UploadBeginGetRequestStreamCallBack(IAsyncResult ar)
{
  string json = "{\"parameter1\":\"test\"}";

  HttpWebRequest webRequest = (HttpWebRequest)(ar.AsyncState);
  using (Stream postStream = webRequest.EndGetRequestStream(ar))
  {
    byte[] byteArray = Encoding.UTF8.GetBytes(json);
    postStream.Write(byteArray, 0, byteArray.Length);
    postStream.Close();
  }
  webRequest.BeginGetResponse(new AsyncCallback(Upload_Completed), webRequest);
}

private void Upload_Completed(IAsyncResult result)
{
  WebRequest request = (WebRequest)(result.AsyncState);
  WebResponse response = request.EndGetResponse(result);
  // Parse response
}

当我得到200时,状态总是"错误"。在进一步挖掘之后,我注意到parameter1始终为null。我有点困惑。有人可以告诉我如何通过WebRequest以编程方式发送parameter1的数据以及代码中的文件吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

伙计,这个很难!

我真的试图找到一种以编程方式将文件上传到MVC动作的方法,但我不能,我很抱歉。 我找到的解决方案将文件转换为字节数组并将其序列化为字符串。

在这里,看看。

这是控制器操作

    [AcceptVerbs(HttpVerbs.Post)]
            public ActionResult uploadFile(string fileName, string fileBytes)
            {
                if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(fileBytes))
                    return Json(new { status = "Error" }, JsonRequestBehavior.AllowGet);

                string[] byteToConvert = fileBytes.Split('.');
                List<byte> fileBytesList = new List<byte>();
    byteToConvert.ToList<string>()
            .Where(x => !string.IsNullOrEmpty(x))
            .ToList<string>()
            .ForEach(x => fileBytesList.Add(Convert.ToByte(x)));

                //Now you can save the bytes list to a file

                return Json(new { status = "Success" }, JsonRequestBehavior.AllowGet);
            }

这是客户端代码(发布文件的人)

public void Upload()
        {
            WebRequest request = HttpWebRequest.Create("http://localhost:7267/Search/uploadFile");
            request.Method = "POST";
            //This is important, MVC uses the content-type to discover the action parameters
            request.ContentType = "application/x-www-form-urlencoded";

            byte[] fileBytes = System.IO.File.ReadAllBytes(@"C:\myFile.jpg");

            StringBuilder serializedBytes = new StringBuilder();

            //Let's serialize the bytes of your file
            fileBytes.ToList<byte>().ForEach(x => serializedBytes.AppendFormat("{0}.", Convert.ToUInt32(x)));

            string postParameters = String.Format("fileName={0}&fileBytes={1}", "myFile.jpg", serializedBytes.ToString());

            byte[] postData = Encoding.UTF8.GetBytes(postParameters);

            using (Stream postStream = request.GetRequestStream())
            {
                postStream.Write(postData, 0, postData.Length);
                postStream.Close();
            }

            request.BeginGetResponse(new AsyncCallback(Upload_Completed), request);
        }

        private void Upload_Completed(IAsyncResult result)
        {
            WebRequest request = (WebRequest)(result.AsyncState);
            WebResponse response = request.EndGetResponse(result);
            // Parse response
        }

Hanselman has a good post关于从网络界面上传文件,这不是你的情况。

如果您需要帮助将字节数组转换回文件,请检查以下帖子:Can a Byte[] Array be written to a file in C#?

希望这有帮助。

如果有人有更好的解决方案,我想看看它。

此致 Calil