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

时间:2013-05-30 09:54:34

标签: c# php post httpwebrequest

我有一个c#函数,用于将文件上传到PHP Web服务。 PHP Web服务期待以下

  • 一个名为UploadFileRequestDto的POST参数,包含一些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()));
        }

1 个答案:

答案 0 :(得分:1)

好的,我发现了问题,

post_max_size
php.ini中的

设置设置为8M,我尝试上传的一些文件执行8M。将此设置更改为16M并重新启动PHP服务。

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