How to send a file and form data with HttpClient in C#

前端 未结 2 532
滥情空心
滥情空心 2020-11-30 12:44

How can I send a file and form data with the HttpClient?

I have two ways to send a file or form data. But I want to send both like an HTML form. How can

相关标签:
2条回答
  • 2020-11-30 13:02

    Here's code I'm using a method to send file and data from console to API

                   
    static async Task uploaddocAsync()
    {
        MultipartFormDataContent form = new MultipartFormDataContent();
        Dictionary<string, string> parameters = new Dictionary<string, string>();
        //parameters.Add("username", user.Username);
        //parameters.Add("FullName", FullName);
        HttpContent DictionaryItems = new FormUrlEncodedContent(parameters);
        form.Add(DictionaryItems, "model");
    
        try
        {
            var stream = new FileStream(@"D:\10th.jpeg", FileMode.Open);
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(@"http:\\xyz.in");
                
            HttpContent content = new StringContent("");
            content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                Name = "uploadedFile1",
                FileName = "uploadedFile1"
            };
            content = new StreamContent(stream);
            form.Add(content, "uploadedFile1"); 
    
            client.DefaultRequestHeaders.Add("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.dsfdsfdsfdsfsdfkhjhjkhjk.vD056hXETFMXYxOaLZRwV7Ny1vj-tZySAWq6oybBr2w");
                     
            var response = client.PostAsync(@"\api\UploadDocuments\", form).Result;
            var k = response.Content.ReadAsStringAsync().Result;
        }
        catch (Exception ex)
        {
    
    
        }
    }
    
    0 讨论(0)
  • 2020-11-30 13:03

    Here's code I'm using to post form information and a csv file

    using (var httpClient = new HttpClient())
    {
        var surveyBytes = ConvertToByteArray(surveyResponse);
    
        httpClient.DefaultRequestHeaders.Add("X-API-TOKEN", _apiToken);
        httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    
        var byteArrayContent =   new ByteArrayContent(surveyBytes);
        byteArrayContent.Headers.ContentType = MediaTypeHeaderValue.Parse("text/csv");
    
        var response = await httpClient.PostAsync(_importUrl, new MultipartFormDataContent
        {
            {new StringContent(surveyId), "\"surveyId\""},
            {byteArrayContent, "\"file\"", "\"feedback.csv\""}
        });
    
        return response;
    }
    

    This is for .net 4.5.

    Note the \" in the MultipartFormDataContent. There is a bug in MultipartFormDataContent.

    In 4.5.1 MultipartFormDataContent wraps the data with the correct quotes.

    Update: This link to the bug no longer works since the have retired Microsoft Connect.

    0 讨论(0)
提交回复
热议问题