ASP.NET WebApi: jak wykonać wieloczęściowy post z przesłaniem pliku za pomocą WebApi HttpClient

Mam usługę WebApi obsługującą upload z prostego formularza, takiego jak ten:

    <form action="/api/workitems" enctype="multipart/form-data" method="post">
        <input type="hidden" name="type" value="ExtractText" />
        <input type="file" name="FileForUpload" />
        <input type="submit" value="Run test" />
    </form>

Jednak nie mogę dowiedzieć się, jak symulować ten sam post za pomocą HttpClient API. Bit FormUrlEncodedContent jest dość prosty, ale jak dodać zawartość pliku z nazwą do posta?

Author: Cheeso, 2012-04-26

3 answers

Po wielu próbach i błędach, oto kod, który faktycznie działa:

using (var client = new HttpClient())
{
    using (var content = new MultipartFormDataContent())
    {
        var values = new[]
        {
            new KeyValuePair<string, string>("Foo", "Bar"),
            new KeyValuePair<string, string>("More", "Less"),
        };

        foreach (var keyValuePair in values)
        {
            content.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
        }

        var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(fileName));
        fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = "Foo.txt"
        };
        content.Add(fileContent);

        var requestUri = "/api/action";
        var result = client.PostAsync(requestUri, content).Result;
    }
}
 115
Author: Michael Teper,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-05 07:12:08

Musisz szukać różnych podklas HttpContent.

Tworzysz wieloformatową zawartość http i dodajesz do niej różne części. W Twoim przypadku masz zawartość tablicy bajtów i Url formularza zakodowanego wzdłuż linii :

HttpClient c = new HttpClient();
var fileContent = new ByteArrayContent(new byte[100]);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                                            {
                                                FileName = "myFilename.txt"
                                            };

var formData = new FormUrlEncodedContent(new[]
                                            {
                                                new KeyValuePair<string, string>("name", "ali"),
                                                new KeyValuePair<string, string>("title", "ostad")
                                            });


MultipartContent content = new MultipartContent();
content.Add(formData);
content.Add(fileContent);
c.PostAsync(myUrl, content);
 10
Author: Aliostad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-27 00:06:57

Dziękuję @ Michael Tepper za odpowiedź.

Musiałem opublikować załączniki do MailGun (dostawcy poczty e-mail) i musiałem go nieco zmodyfikować, aby zaakceptował moje załączniki.

var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(fileName));
fileContent.Headers.ContentDisposition = 
        new ContentDispositionHeaderValue("form-data") //<- 'form-data' instead of 'attachment'
{
    Name = "attachment", // <- included line...
    FileName = "Foo.txt",
};
multipartFormDataContent.Add(fileContent);

Tutaj dla przyszłych odniesień. Dzięki.

 8
Author: ThiagoPXP,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-03 00:34:05