使用HttpClient multipart / form-data发送多文件

时间:2014-10-12 14:20:41

标签: c# httpclient multipartform-data cmultifileupload

我正在尝试使用HttpClient发布multipart / form-data

表单需要一定数量的图片。

代码:

var client = new System.Net.Http.HttpClient();
var content = new MultipartFormDataContent();
var postData = new List<KeyValuePair(string,string)> ();
postData.Add(new KeyValuePair < string, string > ("function", "picture2"));
postData.Add(new KeyValuePair < string, string > ("username ", UserID));
postData.Add(new KeyValuePair < string, string > ("password ", Password));
foreach(var keyValuePair in postData) {
content.Add(new StringContent(keyValuePair.Value),
    String.Format("\"{0}\"", keyValuePair.Key));
}
int x = 1;
foreach(Bitmap item in newpics) {
using(MemoryStream ms = new MemoryStream()) {
    item.Save(ms, ImageFormat.Bmp);
    byte[] bits = ms.ToArray();
    content.Add(new ByteArrayContent(bits), '"' + "pict" + x + '"');
    x += 1;
}
}

问题是只发送了最后一张图片!!

为什么会这样?我错过了什么?以及如何解决这个问题?

提前致谢..

1 个答案:

答案 0 :(得分:0)

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

这是我的榜样。希望它有所帮助:

var path = @&#34; C:\ B2BAssetRoot \ files \ 596086 \ 596086.1.mp4&#34;;

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

            using (var content = new MultipartFormDataContent())
            {
                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();
相关问题