0

我有一个 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# 应用程序上传到此端点。目前,我正在使用以下内容:

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 始终为空。我有点困惑。有人可以告诉我如何通过 WebRequest 以编程方式发送参数 1 的数据以及代码中的文件吗?

谢谢!

4

1 回答 1

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 有一篇关于从 Web 界面上传文件的好帖子,这不是你的情况。

如果您需要帮助将字节数组转换回文件,请查看此线程:Can a Byte[] Array be write to a file in C#?

希望这可以帮助。

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

问候, 卡里尔

于 2012-06-28T02:35:35.830 回答