繁体   English   中英

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

[英]$_POST global empty when uploading a file using HttpWebRequest in C#

我有一个ac#函数,用于将文件上传到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()));
        }

好吧,我发现了问题,

post_max_size

php.ini中的设置设置为8M,而我尝试上传的某些文件超过了8M。 将此设置更改为16M,然后重新启动PHP服务。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM