ASP.NET WebApi: how to perform a multipart post with file upload using WebApi HttpClient

后端 未结 3 2170
我寻月下人不归
我寻月下人不归 2020-11-27 10:47

I have a WebApi service handling an upload from a simple form, like this one:

    
3条回答
  •  没有蜡笔的小新
    2020-11-27 11:20

    You need to look for various subclasses of HttpContent.

    You create a multiform http content and add various parts to it. In your case you have a byte array content and form url encoded along the lines of:

    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("name", "ali"),
                                                    new KeyValuePair("title", "ostad")
                                                });
    
    
    MultipartContent content = new MultipartContent();
    content.Add(formData);
    content.Add(fileContent);
    c.PostAsync(myUrl, content);
    

提交回复
热议问题