C# HttpClient 4.5 multipart/form-data upload

前端 未结 10 891
逝去的感伤
逝去的感伤 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 05:57

    public async Task PassImageWithText(IFormFile files)
    {
        byte[] data;
        string result = "";
        ByteArrayContent bytes;
    
        MultipartFormDataContent multiForm = new MultipartFormDataContent();
    
        try
        {
            using (var client = new HttpClient())
            {
                using (var br = new BinaryReader(files.OpenReadStream()))
                {
                    data = br.ReadBytes((int)files.OpenReadStream().Length);
                }
    
                bytes = new ByteArrayContent(data);
                multiForm.Add(bytes, "files", files.FileName);
                multiForm.Add(new StringContent("value1"), "key1");
                multiForm.Add(new StringContent("value2"), "key2");
    
                var res = await client.PostAsync(_MEDIA_ADD_IMG_URL, multiForm);
            }
        }
        catch (Exception e)
        {
            throw new Exception(e.ToString());
        }
    
        return result;
    }
    
        

    提交回复
    热议问题