How to post form-data IFormFile with HttpClient?

后端 未结 4 1584
暖寄归人
暖寄归人 2021-01-04 07:22

I have backend endpoint Task Post(IFormFile csvFile) and I need to call this endpoint from HttpClient. Currently I am getting Unsuppor

4条回答
  •  失恋的感觉
    2021-01-04 07:30

    Use this snippet:

    const string url = "https://localhost:5001/api/Upload";
    const string filePath = @"C:\Path\To\File.png";
    
    using (var httpClient = new HttpClient())
    {
        using (var form = new MultipartFormDataContent())
        {
            using (var fs = File.OpenRead(filePath))
            {
                using (var streamContent = new StreamContent(fs))
                {
                    using (var fileContent = new ByteArrayContent(await streamContent.ReadAsByteArrayAsync()))
                    {
                        fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
    
                        // "file" parameter name should be the same as the server side input parameter name
                        form.Add(fileContent, "file", Path.GetFileName(filePath));
                        HttpResponseMessage response = await httpClient.PostAsync(url, form);
                    }
                }
            }
        }
    }
    

提交回复
热议问题