C#HttpClient 4.5分段/表单数据上传


145

有谁知道如何使用 HttpClient在.Net 4.5中使用multipart/form-data上传功能?

我在互联网上找不到任何示例。


1
我试过了,但我还不知道如何启动它。我将byteArray添加到内容中,依此类推。我需要某种开始帮助。
IDENT

您可以查看此帖子的答案。(使用代理设置)stackoverflow.com/a/50462636/2123797
埃尔金·塞利克

Answers:


156

我的结果看起来像这样:

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;
              }
          }
     }
}

6
哇,将大文件上传到REST API时,执行此操作非常简单。我不想评论谢谢,但谢谢。这是便携式Windows Phone的8
莱昂佩尔蒂埃

1
对于我来说,这段代码失败了,因为传递给它的边界字符串new MultipartFormDataContent(...)包含无效的边界字符(可能是“ /”分隔符)。没有错误,只有文件没有发布到服务器中-在我的例子中,API控制器中的Context.Request.Files.Count = 0。可能只是一个Nancy问题,但我建议改用类似的方法DateTime.Now.Ticks.ToString("x")
Dunc

7
@MauricioAviles,您的链接已断开。我发现这个很好地解释了这一点: aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong
Kevin Harker

1
如果出现错误:“ 未找到上载的文件 ”,请尝试将keyfileName参数添加到content(在此示例中为bilddateiupload.jpg)。
jhhwilliams

1
@KevinHarker,重读第二个链接。关于不处理HttpClient的段落是指以前的设计。容易混淆。基本上,对于IHttpClientFactory而言,HttpClient Dispose并不会做任何事情(stackoverflow.com/a/54326424/476048),内部处理程序由HttpClientFactory管理。
Berin Loritsch '19

83

它或多或少像这样工作(例如使用图像/ 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);
}

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

完成后,你会发现响应里面的内容HttpResponseMessage.Content,您可以用消耗HttpContent.ReadAs*Async


2
谢谢你的// here you can specify boundary if you need---^:)
sfarbota

1
为什么这不起作用?公共异步Task <string> SendImage(byte [] foto){var requestContent = new MultipartFormDataContent(); var imageContent = new ByteArrayContent(foto); imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse(“ image / jpeg”); requestContent.Add(imageContent,“ foto”,“ foto.jpg”); 字符串url =“ myAddress / myWS / api / Home / SendImage?foto = ”; 等待_client.PostAsync(url,requestContent); 返回“确定”;}
atapi19 '18

1
async第一行和await最后一行之前的行都是不必要的。
1valdis '18 -4-2

对于大文件,将流内容添加到请求中,而不是字节数组。
伊丽莎白

1
@WDRust,带有字节数组,您首先将整个文件加载到内存中,然后将其发送。对于流内容,使用缓冲区读取和发送文件,这在内存方面更加有效。
约瑟夫·布拉哈19'May

53

这是一个如何使用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();
        }
    }
}

11
@Trout您不知道您的代码如何使我今天太开心了!+1

6
这是完整的答案。
VK

2
我知道我们不应该发表感谢信。但这是我所见过的关于如何使用的最佳代码MultipartFormDataContent。先生,您好!
sebagomez

同意 这是唯一包含json字符串和文件作为有效内容内容一部分的答案。
frostshoxx

我的电脑我的测试(WIN7 SP1,IIS 7.5)不Content-TypeContent-Disposition是好的,但Server 2008的R2(IIS 7.5)无法找到文件,这是奇怪的。所以我做答案。
chengzi

18

这是有关如何使用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);
}

12

试试这个对我有用。

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;
}

完美无瑕。正是我在TestServer.CreatClient()针对数据+文件上传的集成测试的.NET Core 方案中所寻找的。
VedranMandić'19

如果方法是HTTPGET,则如何传递formcontent
MBG

@MBG GET请求通常没有约定的请求正文,因此您不能使用GET上传文件(否则就不能上传文件,除非要发送到的服务器非常不寻常-大多数Web服务器都不希望它或不支持它) ,因为没有包含文件或随附表单数据的请求正文。我认为,从理论上讲,没有什么可以阻止这一点在理论上得以实现,只是几乎所有HTTP实现中的约定都是语义上的,GET主要用于检索信息(而不是发送),因此它没有正文
ADyson

9

这是一个对我有用的完整示例。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;

我们该如何发送令牌?请查看此内容:stackoverflow.com/questions/48295877/…–

@Softlion-我在发送前不将其加载到内存中遇到麻烦。如果您知道更好的方法,请在此处发布:stackoverflow.com/questions/52446969/…–
emery.noel

1

预加载器Dotnet 3.0 Core的示例

ProgressMessageHandler processMessageHander = new ProgressMessageHandler();

processMessageHander.HttpSendProgress += (s, e) =>
{
    if (e.ProgressPercentage > 0)
    {
        ProgressPercentage = e.ProgressPercentage;
        TotalBytes = e.TotalBytes;
        progressAction?.Invoke(progressFile);
    }
};

using (var client = HttpClientFactory.Create(processMessageHander))
{
    var uri = new Uri(transfer.BackEndUrl);
    client.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", AccessToken);

    using (MultipartFormDataContent multiForm = new MultipartFormDataContent())
    {
        multiForm.Add(new StringContent(FileId), "FileId");
        multiForm.Add(new StringContent(FileName), "FileName");
        string hash = "";

        using (MD5 md5Hash = MD5.Create())
        {
            var sb = new StringBuilder();
            foreach (var data in md5Hash.ComputeHash(File.ReadAllBytes(FullName)))
            {
                sb.Append(data.ToString("x2"));
            }
            hash = result.ToString();
        }
        multiForm.Add(new StringContent(hash), "Hash");

        using (FileStream fs = File.OpenRead(FullName))
        {
            multiForm.Add(new StreamContent(fs), "file", Path.GetFileName(FullName));
            var response = await client.PostAsync(uri, multiForm);
            progressFile.Message = response.ToString();

            if (response.IsSuccessStatusCode) {
                progressAction?.Invoke(progressFile);
            } else {
                progressErrorAction?.Invoke(progressFile);
            }
            response.EnsureSuccessStatusCode();
        }
    }
}

1
X509Certificate clientKey1 = null;
clientKey1 = new X509Certificate(AppSetting["certificatePath"],
AppSetting["pswd"]);
string url = "https://EndPointAddress";
FileStream fs = File.OpenRead(FilePath);
var streamContent = new StreamContent(fs);

var FileContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
FileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("ContentType");
var handler = new WebRequestHandler();


handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ClientCertificates.Add(clientKey1);
handler.ServerCertificateValidationCallback = (httpRequestMessage, cert, cetChain, policyErrors) =>
{
    return true;
};


using (var client = new HttpClient(handler))
{
    // Post it
    HttpResponseMessage httpResponseMessage = client.PostAsync(url, FileContent).Result;

    if (!httpResponseMessage.IsSuccessStatusCode)
    {
        string ss = httpResponseMessage.StatusCode.ToString();
    }
}

此方案用于通过安全证书将文件上传到API站点
Rajenthiran T

0

我添加了一个代码段,该代码段显示了如何将文件发布到已通过DELETE http动词公开的API。上载带有DELETE http动词的文件并不常见,但可以使用。我已经假定Windows NTLM身份验证可以授权调用。

一个人可能面临的问题是HttpClient.DeleteAsync方法的所有重载都没有参数来HttpContent获取PostAsync方法

var requestUri = new Uri("http://UrlOfTheApi");
using (var streamToPost = new MemoryStream("C:\temp.txt"))
using (var fileStreamContent = new StreamContent(streamToPost))
using (var httpClientHandler = new HttpClientHandler() { UseDefaultCredentials = true })
using (var httpClient = new HttpClient(httpClientHandler, true))
using (var requestMessage = new HttpRequestMessage(HttpMethod.Delete, requestUri))
using (var formDataContent = new MultipartFormDataContent())
{
    formDataContent.Add(fileStreamContent, "myFile", "temp.txt");
    requestMessage.Content = formDataContent;
    var response = httpClient.SendAsync(requestMessage).GetAwaiter().GetResult();

    if (response.IsSuccessStatusCode)
    {
        // File upload was successfull
    }
    else
    {
        var erroResult = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
        throw new Exception("Error on the server : " + erroResult);
    }
}

您需要在C#文件顶部的名称空间下方:

using System;
using System.Net;
using System.IO;
using System.Net.Http;

PS对不起,我的代码中使用了很多块(IDisposable模式)。不幸的是,使用C#构造的语法不支持在单个语句中初始化多个变量。


-3
public async Task<object> PassImageWithText(IFormFile files)
{
    byte[] data;
    string result = "";
    ByteArrayContent bytes;

    MultipartFormDataContent multiForm = new MultipartFormDataContent();

    try
    {
        using (var client = new HttpClient())
        {
            using (var br = new BinaryReader(files.OpenReadStream()))
            {
                data = br.ReadBytes((int)files.OpenReadStream().Length);
            }

            bytes = new ByteArrayContent(data);
            multiForm.Add(bytes, "files", files.FileName);
            multiForm.Add(new StringContent("value1"), "key1");
            multiForm.Add(new StringContent("value2"), "key2");

            var res = await client.PostAsync(_MEDIA_ADD_IMG_URL, multiForm);
        }
    }
    catch (Exception e)
    {
        throw new Exception(e.ToString());
    }

    return result;
}

您可以通过注释自己编写的代码来改善答案
msrd0 '19

好的,msrd!对不起我的新手。我喜欢输入清晰的代码,例如“ Erik Kalkoke”。我将共享我的代码,例如在服务器节点1上通过IFormFile接收图像,并通过类[MultipartFormDataContent]增加一些文本来传递到服务器节点2哦!最后一行是这样的。结果=等待res.Content.ReadAsStringAsync();
开膛手杰克
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.