Aet_Leng
2020-08-06 16:26
采纳率: 87.5%
浏览 918

C# HttpWebRequest multipart/form-data提交的文件始终在From中,如何处理

我想通过HttpWebRequest 向一个借口提交数据以及文件

现在接口已经打通,但是无论我如何调整,上传的文件始终在HttpRequest.Form中

我希望在HttpRequest.Files 中看到我上传的文件

   HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(monitor.ReqUrl);
            req.Method = "POST";
            req.Timeout = 2000000;
            req.KeepAlive = false;
             // 边界符
            var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
            // 边界符
            var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
            // 最后的结束符
            var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");
            // 设置属性
            req.ContentType = "multipart/form-data; boundary=" + boundary;
            //综合内存流
            var memStream = new MemoryStream();
                          // 写入文件
                        const string filePartHeader =
                      "Content-Disposition: form-data; name=\"{0}\";  filename=\"{1}\r\n" +
                       "Content-Type: {2};\r\n\r\n";
                        var header = string.Format(filePartHeader, file.FileName, file.FileName, file.ContentType); 
                         var headerbytes = Encoding.UTF8.GetBytes(header);
                        memStream.Write(headerbytes, 0, headerbytes.Length);
                        var buffer = new byte[1024];
                        int bytesRead; // =0
                        while ((bytesRead = file.InputStream.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            memStream.Write(buffer, 0, bytesRead);
                        }
                                                     // 写入最后的结束边界符
                memStream.Write(endBoundary, 0, endBoundary.Length);
                                   req.ContentLength = memStream.Length;
                memStream.Position = 0;
                var tempBuffer = new byte[memStream.Length];
                memStream.Read(tempBuffer, 0, tempBuffer.Length);
                memStream.Close();
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(tempBuffer, 0, tempBuffer.Length);
                }

Files中没有文件

Form中出现了文件

2条回答 默认 最新

相关推荐 更多相似问题