服务器不读取没有 MIME 类型的请求



我在服务器端读取请求正文的内容时遇到问题。显然,服务器只读取具有内容类型的文件。就像客户端发送带有标头的请求一样:

"Content-Disposition: form-data; name="{0}"rnrn{1}",
                    "myFileDescription",
                    "A sample file description"

它不会在服务器端读取,但如果标头如下所示:

"Content-Disposition: form-data; name="file";"
         + "filename="temp.txt"rn"
         // Add the file's mime-type
         + "Content-type: plain/textrnrn"

然后服务器将读取此标头的内容。我不知道是什么导致了这个问题,我已经在这个问题上创建了几个线程,但没有人给我任何答案。

我的服务器端代码如下所示:

if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }
        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        var httpRequest = HttpContext.Current.Request;

        if (httpRequest.Files.Count > 0)
        {
            foreach (string file in httpRequest.Files)
            {
                var postedFile = httpRequest.Files[file];
                var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
                postedFile.SaveAs(filePath);
                // NOTE: To store in memory use postedFile.InputStream
            }
            return Request.CreateResponse(HttpStatusCode.Created);
        }
        return Request.CreateResponse(HttpStatusCode.BadRequest);
    }

我的客户端代码如下所示:

HttpWebRequest requestToServer = (HttpWebRequest)
WebRequest.Create(url);
        // Define a boundary string
        string boundaryString = "----";
        // Turn off the buffering of data to be written, to prevent
        // OutOfMemoryException when sending data
        requestToServer.AllowWriteStreamBuffering = false;
        // Specify that request is a HTTP post
        requestToServer.Method = WebRequestMethods.Http.Post;
        // Specify that the content type is a multipart request
        requestToServer.ContentType
            = "multipart/form-data; boundary=" + boundaryString;
        // Turn off keep alive
        requestToServer.KeepAlive = false;

        ASCIIEncoding ascii = new ASCIIEncoding();
        string boundaryStringLine = "rn--" + boundaryString + "rn";
        byte[] boundaryStringLineBytes = ascii.GetBytes(boundaryStringLine);
        string lastBoundaryStringLine = "rn--" + boundaryString + "--rn";
        byte[] lastBoundaryStringLineBytes = ascii.GetBytes(lastBoundaryStringLine);
        // Get the byte array of the myFileDescription content disposition
        string myFileDescriptionContentDisposition =string.Format("Content-Disposition: form-data; name="{0}"rnrn{1}",
                    "myFileDescription",
                    "A sample file description");
        byte[] myFileDescriptionContentDispositionBytes
            = ascii.GetBytes(myFileDescriptionContentDisposition);
        string fileUrl = file;
        // Get the byte array of the string part of the myFile content
        // disposition
        string myFileContentDisposition = string.Format(
            "Content-Disposition: form-data;name="{0}"; "
             + "filename="{1}"rnContent-Type: {2}rnrn",
            "myFile", Path.GetFileName(fileUrl), Path.GetExtension(fileUrl));
        byte[] myFileContentDispositionBytes =
            ascii.GetBytes(myFileContentDisposition);

        FileInfo fileInfo = new FileInfo(fileUrl);
        // Calculate the total size of the HTTP request
        long totalRequestBodySize = boundaryStringLineBytes.Length * 2
            + lastBoundaryStringLineBytes.Length
            + myFileDescriptionContentDispositionBytes.Length
            + myFileContentDispositionBytes.Length
            + fileInfo.Length;
        // And indicate the value as the HTTP request content length
        requestToServer.ContentLength = totalRequestBodySize;

        // Write the http request body directly to the server
        using (Stream s = requestToServer.GetRequestStreamWithTimeout(1000000))
        {
            // Send the file description content disposition over to the server
            s.Write(boundaryStringLineBytes, 0, boundaryStringLineBytes.Length);
            s.Write(myFileDescriptionContentDispositionBytes, 0,
                myFileDescriptionContentDispositionBytes.Length);
            // Send the file content disposition over to the server
            s.Write(boundaryStringLineBytes, 0, boundaryStringLineBytes.Length);
            s.Write(myFileContentDispositionBytes, 0,
                myFileContentDispositionBytes.Length);
            // Send the file binaries over to the server, in 1024 bytes chunk
            FileStream fileStream = new FileStream(fileUrl, FileMode.Open,
                FileAccess.Read);
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
            {
                s.Write(buffer, 0, bytesRead);
            } // end while
            fileStream.Close();
            // Send the last part of the HTTP request body
            s.Write(lastBoundaryStringLineBytes, 0, lastBoundaryStringLineBytes.Length);
            WebResponse response = requestToServer.GetResponseWithTimeout(1000000);
            StreamReader responseReader = new StreamReader(response.GetResponseStream());
            string replyFromServer = responseReader.ReadToEnd();
            return replyFromServer;
这是我的一个

偶然错误。我的服务器端代码只读取文件内容,而我的标头包含文件和表单内容。文件内容将需要在服务器上处理 Mime 类型。表单数据不需要 MIME 类型,包含在 HttpContext.Current.Request.Form 中。

最新更新