【问题标题】:C# HTTP RequestC# HTTP 请求
【发布时间】:2011-12-07 03:54:45
【问题描述】:

您好,我在 C# 中发送 HTTP 请求时遇到问题 我想在 HTTP 请求中上传文件,但我不知道该怎么做

这里是html代码:

<form action="/decrypt/upload" method="post" enctype="multipart/form-data">
            <fieldset>
                <p class="formrow file_upload">
                <label for="dlcfile">Container File</label>
                <input type="file" class="file_field" name="dlcfile" id="dlcfile"/>
                <input type="text" value="Click here to select a file..." class="file_overlay" />
                </p>
                <p class="buttonrow"><button type="submit">Submit »</button></p>
            </fieldset>
        </form>

这是我的 C# 代码:

public static void decryptContainer(string path)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://dcrypt.it/decrypt/upload");
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";


        using (StreamWriter writer = new StreamWriter(request.GetRequestStream(), Encoding.ASCII))
        {
            writer.Write("dlcfile=" + path);
        }

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            Console.WriteLine(reader.ReadToEnd());
        }
    }

我知道我必须给参数一个文件,但我只是不知道如何在 C# 中处理它,有人可以帮助我:)

【问题讨论】:

    标签: c# file http upload request


    【解决方案1】:

    与其自己处理请求,不如使用WebClient。这本质上是所有这些 HttpRequest 类的包装类,使事情变得更加容易。如果你切换到这个,你的代码肯定会变得更简单。

    您还应该看看这个答案,它描述了如何使用 C# 将文件发布到网络服务器:

    Send a file via HTTP POST with C#

    或者,使用表单数据:

    Upload files with HTTPWebrequest (multipart/form-data)

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-11
    • 2017-10-03
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    • 2011-05-27
    • 2020-08-30
    相关资源
    最近更新 更多