C#应用程序中的应用程序/表单数据?

时间:2016-12-16 05:17:17

标签: c# http httpwebrequest httpwebresponse

我使用下面的代码使用C#console应用程序将文件上传到url。它不上传文件而且也没有返回错误。

string[] files = new string []{ "C:/test.csv" };


public static string UploadFilesToRemoteUrl(string url, string[] files, NameValueCollection formFields = null)
    {
        string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.ContentType = "multipart/form-data; boundary=" +
                                boundary;
        request.Method = "POST";
        request.KeepAlive = true;

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

        var boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +
                                                                boundary + "\r\n");
        var endBoundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +
                                                                    boundary + "--");


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

        if (formFields != null)
        {
            foreach (string key in formFields.Keys)
            {
                string formitem = string.Format(formdataTemplate, key, formFields[key]);
                byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
                memStream.Write(formitembytes, 0, formitembytes.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++)
        {
            memStream.Write(boundarybytes, 0, boundarybytes.Length);
            var header = string.Format(headerTemplate, "uplTheFile", files[i]);
            var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);

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

            using (var fileStream = new FileStream(files[i], FileMode.Open, FileAccess.Read))
            {
                var buffer = new byte[1024];
                var bytesRead = 0;
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    memStream.Write(buffer, 0, bytesRead);
                }
            }
        }

        memStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
        request.ContentLength = memStream.Length;

        using (Stream requestStream = request.GetRequestStream())
        {
            memStream.Position = 0;
            byte[] tempBuffer = new byte[memStream.Length];
            memStream.Read(tempBuffer, 0, tempBuffer.Length);
            memStream.Close();
            requestStream.Write(tempBuffer, 0, tempBuffer.Length);
        }

        using (var response = request.GetResponse())
        {
            Stream stream2 = response.GetResponseStream();
            StreamReader reader2 = new StreamReader(stream2);
            return reader2.ReadToEnd();
        }
    }

Upload files with HTTPWebrequest (multipart/form-data)

我已经检查了这段代码并且它没有在url中上传文件我被给了,也没有错误返回。

1 个答案:

答案 0 :(得分:1)

此问题已在此处得到解答: Upload files with HTTPWebrequest (multipart/form-data)

另外,请注意,在您的代码中,您实际上是发送字符串"C:/test.csv"而不是文件的内容!您需要打开FileStreamhttps://msdn.microsoft.com/en-us/library/system.io.filestream.aspx)来流式传输其内容。 (这也在上面的答案中有所涉及)