I would like to upload a file on a specific website with C# and the WebClient class. I have this code :
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));
But the problem, on the website the name of the file input is "fichier" and webclient send "file" as name .
I would like it to send :
Content-Disposition: form-data; name="fichier"; filename="csharp.jpg" instead of : Content-Disposition: form-data; name="file"; filename="csharp.jpg"
I didn't find how to modify this filed, some help please ?
If you have .NET 4.5+, you can use the HttpClient
class to do an asynchronous post:
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();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.