Upload files with HTTPWebrequest (multipart/form-data)

后端 未结 21 2572
独厮守ぢ
独厮守ぢ 2020-11-21 04:53

Is there any class, library or some piece of code which will help me to upload files with HTTPWebrequest?

Edit 2:

I do not

21条回答
  •  一向
    一向 (楼主)
    2020-11-21 05:11

    UPDATE: Using .NET 4.5 (or .NET 4.0 by adding the Microsoft.Net.Http package from NuGet) this is possible without external code, extensions, and "low level" HTTP manipulation. Here is an example:

    // Perform the equivalent of posting a form with a filename and two files, in HTML:
    // 
    // // // //
    private async Task UploadAsync(string url, string filename, Stream fileStream, byte [] fileBytes) { // Convert each of the three inputs into HttpContent objects HttpContent stringContent = new StringContent(filename); // examples of converting both Stream and byte [] to HttpContent objects // representing input type file HttpContent fileStreamContent = new StreamContent(fileStream); HttpContent bytesContent = new ByteArrayContent(fileBytes); // Submit the form using HttpClient and // create form data as Multipart (enctype="multipart/form-data") using (var client = new HttpClient()) using (var formData = new MultipartFormDataContent()) { // Add the HttpContent objects to the form data // formData.Add(stringContent, "filename", "filename"); // formData.Add(fileStreamContent, "file1", "file1"); // formData.Add(bytesContent, "file2", "file2"); // Invoke the request to the server // equivalent to pressing the submit button on // a form with attributes (action="{url}" method="post") var response = await client.PostAsync(url, formData); // ensure the request was a success if (!response.IsSuccessStatusCode) { return null; } return await response.Content.ReadAsStreamAsync(); } }

提交回复
热议问题