Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 通过WebRequest将数据和文件上载到ASP.NET MVC 3操作_C#_Asp.net Mvc 3_Webrequest - Fatal编程技术网

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

C# 通过WebRequest将数据和文件上载到ASP.NET MVC 3操作,c#,asp.net-mvc-3,webrequest,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 (upl

我有一个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分时,状态总是“错误”。进一步挖掘之后,我注意到参数1总是空的。我有点困惑。有人能告诉我如何通过WebRequest以编程方式发送参数1的数据以及代码中的文件吗


谢谢大家!

老兄,这次很难

我真的试图找到一种方法,以编程方式将文件上传到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
        }
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult上载文件(字符串文件名、字符串文件字节)
{
if(string.IsNullOrEmpty(文件名)| | string.IsNullOrEmpty(文件字节))
返回Json(新的{status=“Error”},JsonRequestBehavior.AllowGet);
string[]byteToConvert=fileBytes.Split('.');
List fileBytesList=新列表();
byteToConvert.ToList()
.Where(x=>!string.IsNullOrEmpty(x))
托利斯先生()
.ForEach(x=>fileBytesList.Add(Convert.ToByte(x));
//现在可以将字节列表保存到文件中
返回Json(新的{status=“Success”},JsonRequestBehavior.AllowGet);
}
这是客户端代码(发布文件的人)

    [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
        }
public void Upload()
{
WebRequest=HttpWebRequest.Create(“http://localhost:7267/Search/uploadFile");
request.Method=“POST”;
//这一点很重要,MVC使用内容类型来发现动作参数
request.ContentType=“application/x-www-form-urlencoded”;
byte[]fileBytes=System.IO.File.ReadAllBytes(@“C:\myFile.jpg”);
StringBuilder serializedBytes=新StringBuilder();
//让我们序列化文件的字节
fileBytes.ToList().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(后参数);
使用(Stream postStream=request.GetRequestStream())
{
写入(postData,0,postData.Length);
postStream.Close();
}
BeginGetResponse(新的异步回调(上传完成),请求);
}
私有无效上载\u已完成(IAsyncResult结果)
{
WebRequest=(WebRequest)(result.AsyncState);
WebResponse=request.EndGetResponse(结果);
//解析响应
}
关于从web界面上传文件,这不是您的情况

如果需要帮助将字节数组转换回文件,请检查以下线程:

希望这有帮助

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

问候,,
Calil

非常感谢您的尝试。奇怪的是,在我访问byteToConvert.ToList().ForEach(x=>fileBytesList.Add(Convert.ToByte(x))时的控制器操作中;我得到一个“System.FormatException输入字符串的格式不正确。”哥们,我很抱歉。有2个错误(不检查x是否为空,并且调用string.Concat而不是string.Format)。这两段代码都已更新。伙计,非常感谢你的帮助和坚持。现在开始工作了。我不确定如果没有你的帮助我是否能完成这件事。