c# multipart/form-data submit programmatically

前端 未结 4 1240
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-21 06:30

So got an small problem. Im creating an small application to automate an form submission on one website. But the bad thing is that they are using multipart/form-data for tha

4条回答
  •  情书的邮戳
    2020-12-21 07:22

    The best way to send multipart form data in C# is shown in the snippet, here you see that adding different type of content is as easy as adding it to the wrapper multipart content type:

    var documentContent = new MultipartFormDataContent();
    documentContent.Add(new StringContent("AnalyticsPage.xlsx"), "title");
    documentContent.Add(new ByteArrayContent(File.ReadAllBytes("C:\\Users\\awasthi\\Downloads\\AnalyticsPage.xlsx")), "file", "AnalyticsPage.xlsx");
    

    Then just make an api call:

    using (var client = new HttpClient(new HttpClientHandler() { UseDefaultCredentials = true, CookieContainer = new CookieContainer() }))
    {
      response = client.PostAsync(documentAddApi, documentContent).Result;
      var responseContent = response.Content.ReadAsStringAsync().Result;
     }
    

    Here the expectation is that the rest endpoint you are making a call to is accepting a 'title' field for the file and the byte array of the file named 'file'.

提交回复
热议问题