在 C# 中使用 HTTP POST 发送文件 [英] Sending Files using HTTP POST in c#

查看:30
本文介绍了在 C# 中使用 HTTP POST 发送文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小型的 C# web 应用程序.如何获取允许用户通过 HTTP POST 发送文件的 c# 代码.它应该能够发送文本文件、图像文件、excel、csv、doc(所有类型的文件)) 不使用流阅读器等.

I have a small C# web application.How can I get the c# code that allows user to send files by HTTP POST.It should be able to send text files,image files,excel, csv, doc (all types of files) without using stream reader and all.

推荐答案

可以试试下面的代码:

    public void PostMultipleFiles(string url, string[] files)
{
    string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
    httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
    httpWebRequest.Method = "POST";
    httpWebRequest.KeepAlive = true;
    httpWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
    Stream memStream = new System.IO.MemoryStream();
    byte[] boundarybytes =System.Text.Encoding.ASCII.GetBytes("
--" + boundary     +"
");
    string formdataTemplate = "
--" + boundary + "
Content-Disposition:  form-data; name="{0}";

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

";
    memStream.Write(boundarybytes, 0, boundarybytes.Length);
    for (int i = 0; i < files.Length; i++)
    {
        string header = string.Format(headerTemplate, "file" + i, files[i]);
        //string header = string.Format(headerTemplate, "uplTheFile", 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();
    }
    httpWebRequest.ContentLength = memStream.Length;
    Stream requestStream = httpWebRequest.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();
    try
    {
        WebResponse webResponse = httpWebRequest.GetResponse();
        Stream stream = webResponse.GetResponseStream();
        StreamReader reader = new StreamReader(stream);
        string var = reader.ReadToEnd();

    }
    catch (Exception ex)
    {
        response.InnerHtml = ex.Message;
    }
    httpWebRequest = null;
}

这篇关于在 C# 中使用 HTTP POST 发送文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆