C#HttpClient 4.5 multipart/form-data上传

ide*_*ent 128 c# upload multipartform-data .net-4.5 dotnet-httpclient

有没有人知道如何使用HttpClient.Net 4.5 multipart/form-data上传?

我在互联网上找不到任何例子.

ide*_*ent 139

我的结果如下:

public static async Task<string> Upload(byte[] image)
{
     using (var client = new HttpClient())
     {
         using (var content =
             new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture)))
         {
             content.Add(new StreamContent(new MemoryStream(image)), "bilddatei", "upload.jpg");

              using (
                 var message =
                     await client.PostAsync("http://www.directupload.net/index.php?mode=upload", content))
              {
                  var input = await message.Content.ReadAsStringAsync();

                  return !string.IsNullOrWhiteSpace(input) ? Regex.Match(input, @"http://\w*\.directupload\.net/images/\d*/\w*\.[a-z]{3}").Value : null;
              }
          }
     }
}
Run Code Online (Sandbox Code Playgroud)

  • @MauricioAviles,你的链接坏了.我发现这个很好地解释了它:https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/ (7认同)
  • 哇,在将大文件上传到REST API时,这样做要简单得多.我不想对此表示感谢,但谢谢.它适用于Windows Phone 8. (4认同)
  • 如果出现错误:“**找不到上传的文件**”,请尝试将“key”和“fileName”参数添加到“content”(本例中为 _bilddatei_ 和 _upload.jpg_)。 (3认同)

WDR*_*ust 77

它或多或少都像这样(使用image/jpg文件的例子):

async public Task<HttpResponseMessage> UploadImage(string url, byte[] ImageData)
{
    var requestContent = new MultipartFormDataContent(); 
    //    here you can specify boundary if you need---^
    var imageContent = new ByteArrayContent(ImageData);
    imageContent.Headers.ContentType = 
        MediaTypeHeaderValue.Parse("image/jpeg");

    requestContent.Add(imageContent, "image", "image.jpg");

    return await client.PostAsync(url, requestContent);
}
Run Code Online (Sandbox Code Playgroud)

(您可以随意使用requestContent.Add(),查看HttpContent后代以查看要传入的可用类型)

完成后,您将在里面找到HttpResponseMessage.Content可以使用的响应内容HttpContent.ReadAs*Async.

  • 谢谢您的`//,在这里您可以根据需要指定边界--- ^ :) (2认同)

Joh*_*Chu 44

这是如何使用MultipartFormDataContent使用HTTPClient发布字符串和文件流的示例.需要为每个HTTPContent指定Content-Disposition和Content-Type:

这是我的例子.希望能帮助到你:

private static void Upload()
{
    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Add("User-Agent", "CBS Brightcove API Service");

        using (var content = new MultipartFormDataContent())
        {
            var path = @"C:\B2BAssetRoot\files\596086\596086.1.mp4";

            string assetName = Path.GetFileName(path);

            var request = new HTTPBrightCoveRequest()
                {
                    Method = "create_video",
                    Parameters = new Params()
                        {
                            CreateMultipleRenditions = "true",
                            EncodeTo = EncodeTo.Mp4.ToString().ToUpper(),
                            Token = "x8sLalfXacgn-4CzhTBm7uaCxVAPjvKqTf1oXpwLVYYoCkejZUsYtg..",
                            Video = new Video()
                                {
                                    Name = assetName,
                                    ReferenceId = Guid.NewGuid().ToString(),
                                    ShortDescription = assetName
                                }
                        }
                };

            //Content-Disposition: form-data; name="json"
            var stringContent = new StringContent(JsonConvert.SerializeObject(request));
            stringContent.Headers.Add("Content-Disposition", "form-data; name=\"json\"");
            content.Add(stringContent, "json");

            FileStream fs = File.OpenRead(path);

            var streamContent = new StreamContent(fs);
            streamContent.Headers.Add("Content-Type", "application/octet-stream");
            //Content-Disposition: form-data; name="file"; filename="C:\B2BAssetRoot\files\596090\596090.1.mp4";
            streamContent.Headers.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"" + Path.GetFileName(path) + "\"");
            content.Add(streamContent, "file", Path.GetFileName(path));

            //content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");

            Task<HttpResponseMessage> message = client.PostAsync("http://api.brightcove.com/services/post", content);

            var input = message.Result.Content.ReadAsStringAsync();
            Console.WriteLine(input.Result);
            Console.Read();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @Trout你不知道你的代码今天让我如此开心!+1 (8认同)
  • 这是完整的答案. (6认同)
  • 我知道我们不应该发表感谢信。但这是我所见过的关于如何使用MultipartFormDataContent的最佳代码。先生,恭喜您 (2认同)

小智 21

试试这个对我有用。

private static async Task<object> Upload(string actionUrl)
{
    Image newImage = Image.FromFile(@"Absolute Path of image");
    ImageConverter _imageConverter = new ImageConverter();
    byte[] paramFileStream= (byte[])_imageConverter.ConvertTo(newImage, typeof(byte[]));

    var formContent = new MultipartFormDataContent
    {
        // Send form text values here
        {new StringContent("value1"),"key1"},
        {new StringContent("value2"),"key2" },
        // Send Image Here
        {new StreamContent(new MemoryStream(paramFileStream)),"imagekey","filename.jpg"}
    };

    var myHttpClient = new HttpClient();
    var response = await myHttpClient.PostAsync(actionUrl.ToString(), formContent);
    string stringContent = await response.Content.ReadAsStringAsync();

    return response;
}
Run Code Online (Sandbox Code Playgroud)

  • 完美无瑕。正是我在数据+文件上传的集成测试的 .NET Core `TestServer.CreatClient()` 场景中寻找的内容。 (2认同)

Eri*_*ken 9

这是有关如何使用HttpClient上载的另一个示例multipart/form-data

它将文件上传到REST API,并包括文件本身(例如JPG)和其他API参数。该文件是通过本地磁盘直接上传的FileStream

有关完整的示例,请参见此处,包括附加的API特定逻辑。

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);
}
Run Code Online (Sandbox Code Playgroud)


nth*_*xel 8

这是一个适合我的完整示例.boundary请求中的值由.NET自动添加.

var url = "http://localhost/api/v1/yourendpointhere";
var filePath = @"C:\path\to\image.jpg";

HttpClient httpClient = new HttpClient();
MultipartFormDataContent form = new MultipartFormDataContent();

FileStream fs = File.OpenRead(filePath);
var streamContent = new StreamContent(fs);

var imageContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");

form.Add(imageContent, "image", Path.GetFileName(filePath));
var response = httpClient.PostAsync(url, form).Result;
Run Code Online (Sandbox Code Playgroud)