HttpWebRequest,上传文件

时间:2015-11-24 20:58:54

标签: c# file-upload httpwebrequest

我希望有人可以帮助我。我有以下代码,它试图使用HTTPWebRequest将文件上传到服务器。我根本无法使它工作,导致通用的“HTTP错误500内部服务器”错误。

我尝试了不同的迭代,将代码拆分为单独的方法等,但这是代码中最简单的形式。我搜索了高低,但无法发现我做错了什么!

任何帮助都将不胜感激。

    public HttpWebResponse SubmitPOSTRequest(string url, Dictionary<string, object> postData = null, string fileName = "")
    {
        byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + this.FormDataBoundary + "\r\n"); 

        HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);

        wr.ContentType = "multipart/form-data; boundary=" + this.FormDataBoundary;
        wr.Method = "POST";
        wr.UserAgent = "Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)";
        wr.CookieContainer = new CookieContainer();
        wr.Timeout = 600000;

        using (Stream stream = wr.GetRequestStream())
        {
            if (postData != null)
            {
                string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";

                // Loop through for non-file form-data.
                foreach (string key in postData.Keys)
                {
                    stream.Write(boundaryBytes, 0, boundaryBytes.Length);

                    string formitem = string.Format(formdataTemplate, key, postData[key]);
                    byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);

                    stream.Write(formitembytes, 0, formitembytes.Length);
                }
            }

            if (!string.IsNullOrWhiteSpace(fileName))
            {
                stream.Write(boundaryBytes, 0, boundaryBytes.Length);

                string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
                string header = string.Format(headerTemplate, "File", fileName, GetContentType(fileName));
                byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);

                stream.Write(headerbytes, 0, headerbytes.Length);

                FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                byte[] buffer = new byte[4096];
                int bytesRead = 0;

                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    stream.Write(buffer, 0, bytesRead);
                }

                fileStream.Close();
            }

            byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + this.FormDataBoundary + "--\r\n");
            stream.Write(trailer, 0, trailer.Length);;
        }

        return wr.GetResponse() as HttpWebResponse;
    }

0 个答案:

没有答案