• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Http.MultipartFormDataContent类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Net.Http.MultipartFormDataContent的典型用法代码示例。如果您正苦于以下问题:C# MultipartFormDataContent类的具体用法?C# MultipartFormDataContent怎么用?C# MultipartFormDataContent使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



MultipartFormDataContent类属于System.Net.Http命名空间,在下文中一共展示了MultipartFormDataContent类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: sendPost

        public void sendPost()
        {
            // Définition des variables qui seront envoyés
            HttpContent stringContent1 = new StringContent(param1String); // Le contenu du paramètre P1
            HttpContent stringContent2 = new StringContent(param2String); // Le contenu du paramètre P2
            HttpContent fileStreamContent = new StreamContent(paramFileStream);
            //HttpContent bytesContent = new ByteArrayContent(paramFileBytes);

            using (var client = new HttpClient())
            using (var formData = new MultipartFormDataContent())
            {
                formData.Add(stringContent1, "P1"); // Le paramètre P1 aura la valeur contenue dans param1String
                formData.Add(stringContent2, "P2"); // Le parmaètre P2 aura la valeur contenue dans param2String
                formData.Add(fileStreamContent, "FICHIER", "RETURN.xml");
                //  formData.Add(bytesContent, "file2", "file2");
                try
                {
                    var response = client.PostAsync(actionUrl, formData).Result;
                    MessageBox.Show(response.ToString());
                    if (!response.IsSuccessStatusCode)
                    {
                        MessageBox.Show("Erreur de réponse");
                    }
                }
                catch (Exception Error)
                {
                    MessageBox.Show(Error.Message);
                }
                finally
                {
                    client.CancelPendingRequests();
                }
            }
        }
开发者ID:microint,项目名称:WindowsFormsPostRequest,代码行数:34,代码来源:Form1.cs


示例2: File

        public async Task<Models.Media> File(Stream fileStream, string name = "", string description = "", string projectId = null)
        {
            using (var formData = new MultipartFormDataContent())
            {
                AddStringContent(formData, _client.Authentication.FieldName, _client.Authentication.Value);
                AddStringContent(formData, "project_id", projectId);
                AddStringContent(formData, "name", name);
                AddStringContent(formData, "description", description);

                // Add the file stream
                var fileContent = new StreamContent(fileStream);
                fileContent.Headers.Add("Content-Type", "application/octet-stream");
                fileContent.Headers.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"" + name + "\"");
                formData.Add(fileContent, "file", name);

                // HttpClient problem workaround
                var boundaryValue = formData.Headers.ContentType.Parameters.FirstOrDefault(p => p.Name == "boundary");
                if (boundaryValue != null)
                {
                    boundaryValue.Value = boundaryValue.Value.Replace("\"", string.Empty);
                }

                // Upload the file
                var response = await _client.Post(Client.UploadUrl, formData);

                return _client.Hydrate<Models.Media>(response);
            }
        }
开发者ID:GorillaGeek,项目名称:gorilla.wistia,代码行数:28,代码来源:Upload.cs


示例3: upload_image

        static async void upload_image(string path)
        {
            Console.WriteLine("Uploading {0}", path);
            try {
                using (var client = new HttpClient()) {
                    using (var stream = File.OpenRead(path)) {
                        var content = new MultipartFormDataContent();
                        var file_content = new ByteArrayContent(new StreamContent(stream).ReadAsByteArrayAsync().Result);
                        file_content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
                        file_content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                        {
                            FileName = "screenshot.png",
                            Name = "foo",
                        };
                        content.Add(file_content);
                        client.BaseAddress = new Uri("https://pajlada.se/poe/imgup/");
                        var response = await client.PostAsync("upload.php", content);
                        response.EnsureSuccessStatusCode();
                        Console.WriteLine("Done");
                    }
                }

            } catch (Exception) {
                Console.WriteLine("Something went wrong while uploading the image");
            }
        }
开发者ID:pajlada,项目名称:ScreenshotUploader,代码行数:26,代码来源:Program.cs


示例4: Upload

        public Stream Upload(string url, string filename, Stream fileStream)
        {
            HttpContent stringContent = new StringContent(filename);
            HttpContent fileStreamContent = new StreamContent(fileStream);

            using (var handler = new ProgressMessageHandler())
            using (var client = HttpClientFactory.Create(handler))
            using (var formData = new MultipartFormDataContent())
            {
                client.Timeout = new TimeSpan(1, 0, 0); // 1 hour should be enough probably

                formData.Add(fileStreamContent, "file", filename);

                handler.HttpSendProgress += (s, e) =>
                {
                    float prog = (float)e.BytesTransferred / (float)fileStream.Length;
                    prog = prog > 1 ? 1 : prog;

                    if (FileProgress != null)
                        FileProgress(filename, prog);
                };

                var response_raw = client.PostAsync(url, formData);

                var response = response_raw.Result;

                if (!response.IsSuccessStatusCode)
                {
                    return null;
                }
                return response.Content.ReadAsStreamAsync().Result;
            }
        }
开发者ID:hexafluoride,项目名称:UguuSharp,代码行数:33,代码来源:Uploader.cs


示例5: Should_Accept_Only_Text_Content

        public void Should_Accept_Only_Text_Content()
        {
            // Arrange
            Mock<IStorageRepository> storageRepositoryMock;
            Mock<IFileProcessor> fileProcessorMock;
            Mock<IChecksumCalculator> checksumCalculatorMock;
            Mock<IMetadataRepository> metadataRepositoryMock;
            var controller = this.ConfigureController(out storageRepositoryMock, out fileProcessorMock, out checksumCalculatorMock, out metadataRepositoryMock);

            var multipartContent = new MultipartFormDataContent();
            var binaryContent = Enumerable.Repeat(Enumerable.Range(14, 255).ToArray(), 20).SelectMany(x => x.Select(y => y)).Select(x=>(byte)x).ToArray();
            var fileContent = new ByteArrayContent(binaryContent);
            fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = "Test.txt" };
            fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("something/that_we_dont_expect");
            multipartContent.Add(fileContent);
            controller.Request.Content = multipartContent;

            // Act
            Task<IHttpActionResult> task = controller.Post();
            task.Wait();

            // Assert
            GenericValueResult<List<MetadataInfo>> result = task.Result as GenericValueResult<List<MetadataInfo>>;
            result.Should().NotBeNull("Wrong data type was returned from the controller");

            var t = result.Value as IEnumerable<Models.MetadataInfo>;
            t.Should().NotBeNull("Wrong data type was returned as a result of controller's work");

            var informationFromService = t.First();
            informationFromService.Id.Should().NotHaveValue();
            informationFromService.ProcessingResult.Should().Be(UploadController.ContentTypeCannotBeAcceptedMessage);
        }
开发者ID:nikolay-pshenichny,项目名称:SANDBOX-WebAPI-AngularJS,代码行数:32,代码来源:UploadControllerTests.cs


示例6: UploadFileToJira

        private static async Task UploadFileToJira(string file)
        {
            var url = IssueUrl(file);
            var response = await client.GetStringAsync(url);

            dynamic issue = JObject.Parse(response);
            var info = GetIssueInfo(file);

            foreach (var attachment in issue.fields.attachment)
            {
                if (attachment.filename != info.OriginalFilename)
                    continue;

                if (!options.Overwrite)
                {
                    Console.WriteLine($"{issue.key} already contains '{info.OriginalFilename}' skipping...");
                    return;
                }

                Console.WriteLine($"{issue.key} Replacing existing attachment '{info.OriginalFilename}'");
                await client.DeleteAsync(attachment.self.ToString());
            }

            Console.WriteLine($"{issue.key} uploading '{info.OriginalFilename}'");

            var form = new MultipartFormDataContent
            {
                { new StreamContent(File.OpenRead(file)), "\"file\"", info.OriginalFilename }
            };

            await client.PostAsync(IssueUrl(file) + "/attachments", form);
        }
开发者ID:bwegman,项目名称:UploadAttachmentsToJira,代码行数:32,代码来源:Program.cs


示例7: Main

        static void Main(string[] args)
        {
            var message = new HttpRequestMessage();
            var content = new MultipartFormDataContent();
            var files = new List<string> {"WebApiDoc01.png", "WebApiDoc02.png"};

            foreach (var file in files)
            {
                var filestream = new FileStream(file, FileMode.Open);
                var fileName = System.IO.Path.GetFileName(file);
                content.Add(new StreamContent(filestream), "file", fileName);
            }

            message.Method = HttpMethod.Post;
            message.Content = content;
            message.RequestUri = new Uri("http://localhost:8081/api/test/filesNoContentType");

            var client = new HttpClient();
            client.SendAsync(message).ContinueWith(task =>
            {
                if (task.Result.IsSuccessStatusCode)
                {
                    var result = task.Result;
                    Console.WriteLine(result);
                }
            });

            Console.ReadLine();
        }
开发者ID:cihanozhan,项目名称:WebApiFileUpload,代码行数:29,代码来源:Program.cs


示例8: send

        /// <summary>
        /// Assincronouslly send the fields in the list to webServer in url parameter
        /// NextStep: add a percentage of uploaded data!
        /// </summary>
        /// <param name="fields"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        internal static async Task<string> send(List<field> fields, string url)
        {
            HttpClient httpClient = new HttpClient();
            MultipartFormDataContent form = new MultipartFormDataContent();

            foreach(field f in fields)
            {
                if(f.kind == fieldKind.text)
                {
                    form.Add(new StringContent(f.content), f.name);
                }
                else if (f.kind == fieldKind.file)
                {
                    HttpContent content = new ByteArrayContent(f.bytes);
                    content.Headers.Add("Content-Type", f.contentType);
                    form.Add(content, f.name, f.fileName);
                }
            }

            HttpResponseMessage response = await httpClient.PostAsync(url, form);

            response.EnsureSuccessStatusCode();
            httpClient.Dispose();
            return response.Content.ReadAsStringAsync().Result;
        }
开发者ID:luandev,项目名称:csharpFormPost,代码行数:32,代码来源:post.cs


示例9: SendMessageWithImageAsync

        private async static Task<bool> SendMessageWithImageAsync(string message, string chatId, string messageId,
            Stream imageStream)
        {
            var tghttpClient = new HttpClient();
            imageStream.Seek(0, SeekOrigin.Begin);
            var buf = ReadFully(imageStream);

            var imageContent = new ByteArrayContent(buf);
            imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/png");

            // Send Message, as well as image
            var endpointUrl =
                        new Uri(string.Format(RequestTemplate.RpcOpUrl, RequestTemplate.AppId, "sendPhoto"));
            var content = new MultipartFormDataContent();
            /*content.Add(new FormUrlEncodedContent(new List<KeyValuePair<string,string>>
            {
                new KeyValuePair<string, string>("chat_id", chatId),
                new KeyValuePair<string, string>("reply_to_message_id", messageId),
                new KeyValuePair<string, string>("caption", message)
            }));*/
            content.Add(imageContent, "photo", string.Format("{0}.png", Guid.NewGuid()));
            content.Add(new ByteArrayContent(Encoding.UTF8.GetBytes(chatId)),"chat_id");
            content.Add(new ByteArrayContent(Encoding.UTF8.GetBytes(messageId)), "reply_to_message_id");
            content.Add(new ByteArrayContent(Encoding.UTF8.GetBytes(message)), "aptiond");
            var result = await
                tghttpClient.PostAsync(endpointUrl, content);
            var content2 = await result.Content.ReadAsStringAsync();
            return result.IsSuccessStatusCode;
        }
开发者ID:lightstudio,项目名称:tg-cortanabot,代码行数:29,代码来源:Sender.cs


示例10: AttachFiles

        private void AttachFiles(IMail message, MultipartFormDataContent content)
		{
			var files = FetchFileBodies(message);
            foreach (var file in files)
            {
                var ifile = file.Value;
                var fileContent = new StreamContent(ifile.OpenAsync(FileAccess.Read).Result);

                fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                {
                    Name =  "files[" + ifile.Name + "]",
                    FileName = ifile.Name
                };

                fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
                content.Add(fileContent); 
            }
           
            var streamingFiles = FetchStreamingFileBodies(message);
			foreach (KeyValuePair<string, MemoryStream> file in streamingFiles) {
				var name = file.Key;
				var stream = file.Value;
                var fileContent = new StreamContent(stream);
               
                fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                {
                    Name = "files[" + name + "]",
                    FileName = name
                };

                fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
                content.Add(fileContent); 
			}
        }
开发者ID:rstepehenson,项目名称:sendgridplus-csharp,代码行数:34,代码来源:Web.cs


示例11: Upload

        private static async Task<HttpStatusCode> Upload()
        {
            var files = new List<string>();

            files.Add(@"c:\temp\midi.xml");
            files.Add(@"c:\temp\maxi.xml");
            files.Add(@"c:\temp\efti.xml");

            var apiUri = string.Format("https://api-dev.qbranch.se/api/customers/{0}/tickets/{1}/attachments",
                                       customerId, ticketId);

            var message = new HttpRequestMessage();
            message.RequestUri = new Uri(apiUri);
            message.Headers.Add("qnet-api-key", apiKey);
            message.Method = HttpMethod.Post;

            var content = new MultipartFormDataContent();
            foreach (var file in files)
            {
                var filestream = new FileStream(file, FileMode.Open);
                var fileName = Path.GetFileName(file);
                content.Add(new StreamContent(filestream), "file", fileName);
            }

            message.Content = content;

            using (var client = new HttpClient())
            {
                var response = await client.SendAsync(message);
                return response.StatusCode;
            }
        }
开发者ID:qbranch-code,项目名称:qnet.integration,代码行数:32,代码来源:Program.cs


示例12: Sign

 public static RequestResponse Sign(byte[] document, string phone, string code)
 {
     using (var client = new HttpClient())
     {
         using (var content =
             new MultipartFormDataContent("Upload----" + DateTime.Now))
         {
             content.Add(new StringContent("pdf"), "type");
             content.Add(new StringContent(phone), "phone");
             content.Add(new StringContent(code), "code");
             content.Add(new StringContent("true"), "timestamp");
             content.Add(new StringContent("Vardas Pavardenis"), "pdf[contact]");
             content.Add(new StringContent("Test"), "pdf[reason]");
             content.Add(new StringContent("Vilnius"), "pdf[location]");
             content.Add(new StringContent("test.pdf"), "pdf[files][0][name]");
             content.Add(new StringContent(Convert.ToBase64String(document)), "pdf[files][0][content]");
             content.Add(
                 new StringContent(
                     BitConverter.ToString(SHA1.Create().ComputeHash(document)).Replace("-", "").ToLower()),
                 "pdf[files][0][digest]");
             using (
                 var message =
                     client.PostAsync("https://developers.isign.io/mobile/sign.json?access_token=" + Api.accessToken,
                         content))
             {
                 var input = message.Result;
                 var serializator = new DataContractJsonSerializer(typeof(RequestResponse));
                 return (RequestResponse)serializator.ReadObject(input.Content.ReadAsStreamAsync().Result);
             }
         }
     }
 }
开发者ID:NerijusV,项目名称:dotnet-example,代码行数:32,代码来源:Program.cs


示例13: GetPackagesStatus

        public static void GetPackagesStatus()
        {
            var client = new HttpClient();

            List<Package> _packages = Databases.serverModel.PackageSet.Where(x => x.Labeled == true && x.Package_id == null).ToList();

            foreach (Package p in _packages)
            {
                MediaLogBarcodePackage package = new MediaLogBarcodePackage();
                package.user = "87";
                package.package = new MediaLogBarcodePack { package_id = p.Temporary_package_id };
                string json = JsonConvert.SerializeObject(package);

                MultipartFormDataContent form = new MultipartFormDataContent();
                StringContent cont = new StringContent(json);
                form.Add(new StringContent(json), "pack");
                HttpResponseMessage response = client.PostAsync("http://csomagteszt.media-log.hu/packages/get_status", form).Result;
                response.EnsureSuccessStatusCode();
                string sd = response.Content.ReadAsStringAsync().Result;//164058, 000000000009
                if (sd.StartsWith("OK"))
                {
                    p.Status = sd.Remove(0, 4);
                    Databases.serverModel.SaveChanges();
                }
                else
                {
                    //gáz van
                }
            }
        }
开发者ID:pellicerrobert,项目名称:IRIS,代码行数:30,代码来源:MediaLog.cs


示例14: GetCaptchaStr

        public string GetCaptchaStr(byte[] imagefile)
        {
            try
            {
                //var result = httpClient.GetAsync("http://poster.de-captcher.com/").Result;
                //result.Dispose();

                MultipartFormDataContent content = new MultipartFormDataContent();
                var values = new[]
                {
                    new KeyValuePair<string, string>("function", "picture2"),
                    new KeyValuePair<string, string>("username", username),
                    new KeyValuePair<string, string>("password", password),
                    new KeyValuePair<string, string>("pict_type", "0"),
                    new KeyValuePair<string, string>("submit", "Send"),
                };
                foreach (var keyValuePair in values)
                {
                    content.Add(new StringContent(keyValuePair.Value),
                        String.Format("\"{0}\"", keyValuePair.Key));
                }
                content.Add(new StreamContent(new MemoryStream(imagefile)), "pict");
                var result = httpClient.PostAsync("http://poster.de-captcher.com/", content).Result;
                string strContent = result.Content.ReadAsStringAsync().Result;
                major = strContent.Split('|')[1];
                min = strContent.Split('|')[2];
                return strContent.Split('|')[5];
            }
            catch
            {
                return "";
            }
        }
开发者ID:chinhdd,项目名称:VisualVisaPoint,代码行数:33,代码来源:DBC.cs


示例15: GetBalance

 public string GetBalance()
 {
     try
     {
         MultipartFormDataContent content = new MultipartFormDataContent();
         var values = new[]
         {
             new KeyValuePair<string, string>("function", "balance"),
             new KeyValuePair<string, string>("username", username),
             new KeyValuePair<string, string>("password", password),
             new KeyValuePair<string, string>("submit", "Send"),
         };
         foreach (var keyValuePair in values)
         {
             content.Add(new StringContent(keyValuePair.Value),
                 String.Format("\"{0}\"", keyValuePair.Key));
         }
         var result = httpClient.PostAsync("http://poster.de-captcher.com/", content).Result;
         return result.Content.ReadAsStringAsync().Result;
     }
     catch
     {
         return "";
     }
 }
开发者ID:chinhdd,项目名称:VisualVisaPoint,代码行数:25,代码来源:DBC.cs


示例16: media_upload

        //TODO: Update response object 
        public static async Task<Upload> media_upload(this Api api, Command command, long total_bytes, string media_data = "", byte[] media = null, string media_type = "", long media_id = -1, int segment_index = 0, IEnumerable<string> additional_owners = null)
        {
            var uri = "https://upload.twitter.com/1.1/media/upload.json";

            var client = new HttpClient(new MessageHandler(api.Token));
            var request = new HttpRequestMessage(HttpMethod.Post, uri);

            var content = new MultipartFormDataContent();

            content.Add(new StringContent(command.ToString()), "command");

            if (media_id != -1) content.Add(new StringContent(media_id.ToString()), "media_id");
            if (segment_index != 0) content.Add(new StringContent(segment_index.ToString()), "segment_index");
            if (!string.IsNullOrEmpty(media_type)) content.Add(new StringContent(media_type), "media_type");

            if (total_bytes != -1) content.Add(new StringContent(total_bytes.ToString()), "total_bytes");

            if (!string.IsNullOrEmpty(media_data)) content.Add(new StringContent(media_data), "media_data");
            if (media != null) content.Add(new ByteArrayContent(media), "media");

            if (additional_owners != null && additional_owners.Any())
            {
                content.Add(new StringContent(string.Join(",", additional_owners)), "additional_owners");
            }

            request.Content = content;

            var response = await client.SendAsync(request);

            var json = await response.Content.ReadAsStringAsync();

            var result = JsonConvert.DeserializeObject<Upload>(json);

            return result;
        }
开发者ID:dotnetnoobie,项目名称:DnxTweet,代码行数:36,代码来源:Media.cs


示例17: UpdateStatus

		/// <summary>
		/// メディア付きのツイートを投稿します。
		/// </summary>
		public static async Task<Status> UpdateStatus(
			this TwitterToken token, string status, string[] mediaPaths, StatusId? inReplyToStatusId = null)
		{
			// media が空だったら通常の投稿に切り替える
			if (!mediaPaths.HasValue()) return await token.UpdateStatus(status, inReplyToStatusId);

			var endpoint = token.Endpoints["statuses/update_with_media"];

			using (var client = token.GetClient())
			using (var content = new MultipartFormDataContent { { new StringContent(status), "\"status\"" } })
			{
				if (inReplyToStatusId.HasValue)
				{
					content.Add(new StringContent(inReplyToStatusId.ToString()), "\"in_reply_to_status_id\"");
				}
				foreach (var path in mediaPaths)
				{
					var media = File.ReadAllBytes(path);
					var filename = Path.GetFileName(path);
					content.Add(new ByteArrayContent(media), "media[]", "\"" + filename + "\"");
				}

				return await client.PostAsyncEx(
					endpoint.Definition.Url,
					content,
					res => endpoint.RateLimit.Set(res.Headers),
					json => Status.Parse(json, StatusSource.Update),
					() => token.FallbackToken.UpdateStatus(status, mediaPaths, inReplyToStatusId));
			}
		}
开发者ID:Grabacr07,项目名称:Mukyutter.Old,代码行数:33,代码来源:RestApi_Tweets.cs


示例18: UploadFile

        /// <summary>
        /// Uploads a file to the specified endpoint
        /// </summary>
        /// <param name="token">The authentication token</param>
        /// <param name="path">The endpoint to invoke</param>
        /// <param name="filename">The local file system path to the file</param>
        /// <param name="contentType">The mime-type</param>
        /// <returns>The result of the operation</returns>
        internal async Task<string> UploadFile(AuthToken token, string path, string filename, string contentType)
        {
            using (HttpClient client = new HttpClient())
            {
                HttpRequestMessage message = new HttpRequestMessage();
                message.Method = HttpMethod.Post;
                message.RequestUri = new Uri($"{_baseAddress}/{path}");
                message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token.Token);
                

                var content =
                    new MultipartFormDataContent("Upload----" + DateTime.Now.ToString(CultureInfo.InvariantCulture));
          

                var streamContent = new StreamContent(File.OpenRead(filename));
                streamContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
                content.Add(streamContent, Path.GetFileName(filename), Path.GetFileName(filename));
                message.Content = content;

                var response =
                    await client.SendAsync(message);

                if (response.IsSuccessStatusCode)
                {
                    return await response.Content.ReadAsStringAsync();

                }
                else
                {
                    throw new ApplicationException($"{response.StatusCode} {response.ReasonPhrase}");
                }
            }

        }
开发者ID:elastacloud,项目名称:Brisk4GamesSDK,代码行数:42,代码来源:HttpHelper.cs


示例19: SendPostFileRequest

        public async Task<string> SendPostFileRequest(string url, NameValueCollection formData, IEnumerable<KeyValuePair<string, byte[]>> fileData)
        {
            // this.txtResponse.Text = string.Empty;
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));//设定要响应的数据格式
                using (var content = new MultipartFormDataContent())//表明是通过multipart/form-data的方式上传数据
                {
                    var formDatas = this.GetFormDataByteArrayContent(formData);//获取键值集合对应的ByteArrayContent集合
                    var files = this.GetFileByteArrayContent(fileData);//获取文件集合对应的ByteArrayContent集合
                    Action<List<ByteArrayContent>> act = (dataContents) =>
                     {//声明一个委托,该委托的作用就是将ByteArrayContent集合加入到MultipartFormDataContent中
                         foreach (var byteArrayContent in dataContents)
                         {
                             content.Add(byteArrayContent);
                         }
                     };

                    act(formDatas);//执行act
                    act(files);//执行act
                    try
                    {
                        var response = await client.PostAsync(url, content);//post请求
                        response.EnsureSuccessStatusCode();

                        return await response.Content.ReadAsStringAsync();
                    }
                    catch (Exception ex)
                    {
                        return null;
                    }
                }
            }
        }
开发者ID:BiaoLiu,项目名称:YLP.UWP.TOOLS,代码行数:34,代码来源:HttpRequestClient.cs


示例20: RunClient

        static async void RunClient()
        {
            HttpClient client = new HttpClient();

            // Issue MIME multipart POST request with a MIME multipart message containing a single
            // body part with StringContent.
            StringContent content = new StringContent("Hello World", Encoding.UTF8, "text/plain");
            MultipartFormDataContent formData = new MultipartFormDataContent();
            formData.Add(content, "file", "HelloWorld.txt");

            Console.WriteLine("Uploading data to store...");
            HttpResponseMessage postResponse = await client.PostAsync(_addres, formData);

            postResponse.EnsureSuccessStatusCode();
            JArray postResult = await postResponse.Content.ReadAsAsync<JArray>();
            string location = postResult[0].Value<string>("Location");

            // Issue GET request to get the content back from the store
            Console.WriteLine("Retrieving data from store: {0}", location);
            HttpResponseMessage getResponse = await client.GetAsync(location);

            getResponse.EnsureSuccessStatusCode();
            string result = await getResponse.Content.ReadAsStringAsync();
            Console.WriteLine("Received response: {0}", result);
        }
开发者ID:andreychizhov,项目名称:microsoft-aspnet-samples,代码行数:25,代码来源:Program.cs



注:本文中的System.Net.Http.MultipartFormDataContent类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Http.MultipartFormDataStreamProvider类代码示例发布时间:2022-05-26
下一篇:
C# Http.HttpResponseMessage类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap