C# HttpClient 4.5 multipart/form-data upload

前端 未结 10 1081
逝去的感伤
逝去的感伤 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条回答
  •  萌比男神i
    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);
    }
    

提交回复
热议问题