在c#中使用HttpWebRequest上传文件时,$_POST全局为空

本文关键字:POST 全局 文件 HttpWebRequest | 更新日期: 2023-09-27 18:16:07

我有一个c#函数,用于将文件上传到PHP web服务。PHP web服务需要以下内容

  • POST参数UploadFileRequestDto包含一些XML数据
  • 文件流

由于某些奇怪的原因,$_POST参数只在某些时候包含UploadFileRequestDto。如果看

的内容
file_get_contents("php://input"))

我可以看到请求是通过UploadFileRequestDto包括预期的。

print_r($_REQUEST)

返回一个空数组。

谁能帮我解决这个问题,我的c#函数是规定在下面

public string UploadFile(UploadFileRequestDto uploadFileRequestDto,string fileToUpload, string fileUploadEndpoint)
    {
        try
        {
            var request = (HttpWebRequest)WebRequest.Create(fileUploadEndpoint);
            request.ReadWriteTimeout = 1000 * 60 * 10;
            request.Timeout = 1000 * 60 * 10;
            request.KeepAlive = false;
            var boundary = "B0unD-Ary";
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method = "POST";
            var postData = "--" + boundary + "'r'nContent-Disposition: form-data;";
            postData += "name='"UploadFileRequestDto'"'r'n'r'n";
            postData += string.Format("{0}'r'n", SerializeUploadfileRequestDto(uploadFileRequestDto));
            postData += "--" + boundary + "'r'n";
            postData += "--" + boundary + "'r'nContent-Disposition: form-data;name='"file'";filename='"" + Path.GetFileName(fileToUpload) + "'"'r'n";
            postData += "Content-Type: multipart/form-data'r'n'r'n";
            var byteArray = Encoding.UTF8.GetBytes(postData);
            byte[] boundaryBytes = Encoding.ASCII.GetBytes("'r'n--" + boundary + "'r'n");
            byte[] filedata = null;
            using (var reader = new BinaryReader(File.OpenRead(fileToUpload)))
            {
                filedata = reader.ReadBytes((int)reader.BaseStream.Length);
            }
            request.ContentLength = byteArray.Length + filedata.Length + boundaryBytes.Length;
            request.GetRequestStream().Write(byteArray, 0, byteArray.Length);
            request.GetRequestStream().Write(filedata, 0, filedata.Length);
            request.GetRequestStream().Write(boundaryBytes, 0, boundaryBytes.Length);
            var response = request.GetResponse();
            var data = response.GetResponseStream();
            var sReader = new StreamReader(data);
            var sResponse = sReader.ReadToEnd();
            response.Close();
            return sResponse.TrimStart(new char[] { ''r', ''n' });
        }
        catch (Exception ex)
        {
            LogProvider.Error(string.Format("OzLib.Infrastructure : WebHelper : public string UploadFile(UploadFileRequestDto uploadFileRequestDto, string fileUploadEndpoint) : Exception = {0}", ex.ToString()));
        }

在c#中使用HttpWebRequest上传文件时,$_POST全局为空

我找到问题了,

post_max_size
php.ini中的

设置设置为8M,而我试图上传的一些文件超过了8M。将此设置更改为16M并重新启动PHP服务。

当文件大小超过设置的限制时,$_POST全局变量为空。