【问题标题】:C# Change content-disposition with webclientC# 使用 webclient 更改内容配置
【发布时间】:2014-06-02 04:29:51
【问题描述】:

我想使用 C# 和 WebClient 类在特定网站上上传文件。我有这个代码:

 Console.Write("\nPlease enter the URI to post data to : ");

            String uriString = "http://www.noelshack.com/api.php";
          //  String uriString = "http://127.0.0.1/upload.php";


            WebClient myWebClient = new WebClient();
            string fileName = lst_path[0];
            byte[] responseArray = myWebClient.UploadFile(uriString,"POST", fileName);

            MessageBox.Show("\nretour:" + System.Text.Encoding.ASCII.GetString(responseArray));

但问题是,在网站上输入文件的名称是“fichier”,webclient 发送“文件”作为名称。

我想发送:

内容配置:表单数据;名称=“fichier”;文件名="csharp.jpg" 代替 : 内容处置:表单数据;名称=“文件”;文件名="csharp.jpg"

我没有找到如何修改这个文件,请帮忙?

【问题讨论】:

  • 反编译使用System.Net.WebClient.OpenFileInternalSystem.Net.WebClient.UploadFile,表明Content-Disposition: form-data; name="file"; filename="是硬编码的。您将需要使用另一种方法。

标签: c# upload webclient content-disposition


【解决方案1】:

如果你有 .NET 4.5+,你可以使用 HttpClient 类来做一个异步发布:

async Task<string> UploadFileAsync(string[] lst_path)
{
    string uriString = "http://www.noelshack.com/api.php";
    string fileName = lst_path[0];
    using (HttpClient client = new HttpClient())
    using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
    using (MultipartFormDataContent form = new MultipartFormDataContent())
    using (StreamContent sc = new StreamContent(fs))
    {
        form.Add(sc, "fichier", fileName);
        HttpResponseMessage response = await client.PostAsync(uriString, form);
        response.EnsureSuccessStatusCode();
        return await response.Content.ReadAsStringAsync();
    }
}

【讨论】:

猜你喜欢
  • 2012-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-12
  • 1970-01-01
  • 1970-01-01
  • 2016-06-27
  • 2021-12-18
相关资源
最近更新 更多