我想用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发送的文件名则是"file"。
我希望它发送:
内容处置:表单数据;name="fichier";filename="csharp.jpg"而不是:内容处置:表单数据;name="file";filename="csharp.jpg"
我没有找到如何修改这个文件,请提供一些帮助?
如果您有.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();
}
}