C# HttpClient 4.5 multipart/form-data upload

前端 未结 10 847
逝去的感伤
逝去的感伤 2020-11-22 05:39

Does anyone know how to use the HttpClient in .Net 4.5 with multipart/form-data upload?

I couldn\'t find any examples on the internet.

相关标签:
10条回答
  • 2020-11-22 06:09

    This is an example of how to post string and file stream with HTTPClient using MultipartFormDataContent. The Content-Disposition and Content-Type need to be specified for each HTTPContent:

    Here's my example. Hope it helps:

    private static void Upload()
    {
        using (var client = new HttpClient())
        {
            client.DefaultRequestHeaders.Add("User-Agent", "CBS Brightcove API Service");
    
            using (var content = new MultipartFormDataContent())
            {
                var path = @"C:\B2BAssetRoot\files\596086\596086.1.mp4";
    
                string assetName = Path.GetFileName(path);
    
                var request = new HTTPBrightCoveRequest()
                    {
                        Method = "create_video",
                        Parameters = new Params()
                            {
                                CreateMultipleRenditions = "true",
                                EncodeTo = EncodeTo.Mp4.ToString().ToUpper(),
                                Token = "x8sLalfXacgn-4CzhTBm7uaCxVAPjvKqTf1oXpwLVYYoCkejZUsYtg..",
                                Video = new Video()
                                    {
                                        Name = assetName,
                                        ReferenceId = Guid.NewGuid().ToString(),
                                        ShortDescription = assetName
                                    }
                            }
                    };
    
                //Content-Disposition: form-data; name="json"
                var stringContent = new StringContent(JsonConvert.SerializeObject(request));
                stringContent.Headers.Add("Content-Disposition", "form-data; name=\"json\"");
                content.Add(stringContent, "json");
    
                FileStream fs = File.OpenRead(path);
    
                var streamContent = new StreamContent(fs);
                streamContent.Headers.Add("Content-Type", "application/octet-stream");
                //Content-Disposition: form-data; name="file"; filename="C:\B2BAssetRoot\files\596090\596090.1.mp4";
                streamContent.Headers.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"" + Path.GetFileName(path) + "\"");
                content.Add(streamContent, "file", Path.GetFileName(path));
    
                //content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
    
                Task<HttpResponseMessage> message = client.PostAsync("http://api.brightcove.com/services/post", content);
    
                var input = message.Result.Content.ReadAsStringAsync();
                Console.WriteLine(input.Result);
                Console.Read();
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 06:10

    Here is another example on how to use HttpClient to upload a multipart/form-data.

    It uploads a file to a REST API and includes the file itself (e.g. a JPG) and additional API parameters. The file is directly uploaded from local disk via FileStream.

    See here for the full example including additional API specific logic.

    public static async Task UploadFileAsync(string token, string path, string channels)
    {
        // we need to send a request with multipart/form-data
        var multiForm = new MultipartFormDataContent();
    
        // add API method parameters
        multiForm.Add(new StringContent(token), "token");
        multiForm.Add(new StringContent(channels), "channels");
    
        // add file and directly upload it
        FileStream fs = File.OpenRead(path);
        multiForm.Add(new StreamContent(fs), "file", Path.GetFileName(path));
    
        // send request to API
        var url = "https://slack.com/api/files.upload";
        var response = await client.PostAsync(url, multiForm);
    }
    
    0 讨论(0)
  • 2020-11-22 06:12

    I'm adding a code snippet which shows on how to post a file to an API which has been exposed over DELETE http verb. This is not a common case to upload a file with DELETE http verb but it is allowed. I've assumed Windows NTLM authentication for authorizing the call.

    The problem that one might face is that all the overloads of HttpClient.DeleteAsync method have no parameters for HttpContent the way we get it in PostAsync method

    var requestUri = new Uri("http://UrlOfTheApi");
    using (var streamToPost = new MemoryStream("C:\temp.txt"))
    using (var fileStreamContent = new StreamContent(streamToPost))
    using (var httpClientHandler = new HttpClientHandler() { UseDefaultCredentials = true })
    using (var httpClient = new HttpClient(httpClientHandler, true))
    using (var requestMessage = new HttpRequestMessage(HttpMethod.Delete, requestUri))
    using (var formDataContent = new MultipartFormDataContent())
    {
        formDataContent.Add(fileStreamContent, "myFile", "temp.txt");
        requestMessage.Content = formDataContent;
        var response = httpClient.SendAsync(requestMessage).GetAwaiter().GetResult();
    
        if (response.IsSuccessStatusCode)
        {
            // File upload was successfull
        }
        else
        {
            var erroResult = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
            throw new Exception("Error on the server : " + erroResult);
        }
    }
    

    You need below namespaces at the top of your C# file:

    using System;
    using System.Net;
    using System.IO;
    using System.Net.Http;
    

    P.S. Sorry about so many using blocks(IDisposable pattern) in my code. Unfortunately, the syntax of using construct of C# doesn't support initializing multiple variables in single statement.

    0 讨论(0)
  • 2020-11-22 06:14

    my result looks like this:

    public static async Task<string> Upload(byte[] image)
    {
         using (var client = new HttpClient())
         {
             using (var content =
                 new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
             {
                 content.Add(new StreamContent(new MemoryStream(image)), "bilddatei", "upload.jpg");
    
                  using (
                     var message =
                         await client.PostAsync("http://www.directupload.net/index.php?mode=upload", content))
                  {
                      var input = await message.Content.ReadAsStringAsync();
    
                      return !string.IsNullOrWhiteSpace(input) ? Regex.Match(input, @"http://\w*\.directupload\.net/images/\d*/\w*\.[a-z]{3}").Value : null;
                  }
              }
         }
    }
    
    0 讨论(0)
提交回复
热议问题