使用HttpWebRequest上传文件

时间:2012-02-10 10:07:25

标签: c# httpwebrequest

这是我的代码:

private void UploadFilesToRemoteUrl(string url, string[] files, string logpath, NameValueCollection nvc)
        {
            long length = 0;
            string boundary = "----------------------------" +
            DateTime.Now.Ticks.ToString("x");

            HttpWebRequest httpWebRequest2 = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest2.ContentType = "multipart/form-data; boundary=" + boundary;
            httpWebRequest2.Method = "POST";
            httpWebRequest2.KeepAlive = true;
            httpWebRequest2.Credentials = System.Net.CredentialCache.DefaultCredentials;

            Stream memStream = new System.IO.MemoryStream();

            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");


            string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";

            foreach(string key in nvc.Keys)
            {
                string formitem = string.Format(formdataTemplate, key, nvc[key]);
                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                memStream.Write(formitembytes, 0, formitembytes.Length);
            }


            memStream.Write(boundarybytes,0,boundarybytes.Length);

            string headerTemplate = "Content-Disposition: form-data; name=\"{0}\";filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";

            for(int i=0;i<files.Length;i++)
            {

                string header = string.Format(headerTemplate,"file"+i,files[i]);

                byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);

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

                FileStream fileStream = new FileStream(files[i], FileMode.Open,
                FileAccess.Read);
                byte[] buffer = new byte[1024];

                int bytesRead = 0;

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

                memStream.Write(boundarybytes,0,boundarybytes.Length);
                fileStream.Close();
            }

            httpWebRequest2.ContentLength = memStream.Length;

            Stream requestStream = httpWebRequest2.GetRequestStream();

            memStream.Position = 0;
            byte[] tempBuffer = new byte[memStream.Length];
            memStream.Read(tempBuffer,0,tempBuffer.Length);
            memStream.Close();
            requestStream.Write(tempBuffer,0,tempBuffer.Length );
            requestStream.Close();


            WebResponse webResponse2 = httpWebRequest2.GetResponse();
            Stream stream2 = webResponse2.GetResponseStream();
            StreamReader reader2 = new StreamReader(stream2);

            MessageBox.Show(reader2.ReadToEnd());

            webResponse2.Close();
            httpWebRequest2 = null;
            webResponse2 = null;

        }

以下是我的称呼方式:

string[] filenames = new string[] { @"C:\Users\John\Desktop\ex.txt" };
NameValueCollection nvc = new NameValueCollection();
nvc.Add("cmd", "new");
nvc.Add("sTitle", "bugX");
nvc.Add("token", "someToken");
UploadFilesToRemoteUrl("https://myUrl.fogbugz.com/api.asp", filenames, "", nvc);

一切正常,但文件未上传。

我也试过这段代码:

http://stackoverflow.com/questions/566462/upload-files-with-httpwebrequest-multipart-form-data

同样的事情发生了。如何解决这个问题?

以下是服务器的响应:

<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<response>
    <case ixBug=\"123486\" operations=\"edit,assign,resolve,email,remind\"></case>
</response>

1 个答案:

答案 0 :(得分:0)

您只是向服务器发送流,如果您不从服务器端为我们提供任何代码,则无法知道服务器上发生了什么。我想你已经忘记了在服务器端接收和创建文件。

如果这不是问题,我建议你获得宝贵的工具小提琴,并开始捕捉你的httprequests并查看它们包含的内容。