当前位置: 首页>>代码示例>>C#>>正文


C# Http.ByteArrayContent类代码示例

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


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

示例1: 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

示例2: SendAddressesToApi

        public string SendAddressesToApi(string csvPath)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(CensusBatchGeoCodeUri);
                var content = new MultipartFormDataContent();

                var fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes("addresses.csv"));
                fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                {
                    Name = "addressFile",
                    FileName = "addresses.csv"
                };
                fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
                content.Add(fileContent);

                // Not a FormUrlEncodedContent class due to an ostensible bug in census API that
                // rejects key/value formatting and requires 'benchmark' in a 'name' field
                var benchMarkContent = new StringContent("9");
                benchMarkContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                {
                    Name = "benchmark"
                };
                content.Add(benchMarkContent);

                var result = client.PostAsync("", content).Result;
                string resultContent = result.Content.ReadAsStringAsync().Result;
                return resultContent;
            }
        }
开发者ID:UpQuark,项目名称:GeoNerves,代码行数:30,代码来源:GeoNervesApiAgent.cs

示例3: CreateBlob

        public void CreateBlob(Guid id, byte[] content, string fileName)
        {
            var bytes = new ByteArrayContent(content);
            bytes.Headers.ContentDisposition = new ContentDispositionHeaderValue("file") { FileName = fileName };
            bytes.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

            var request = new HttpRequestMessage(HttpMethod.Post, String.Format("/blobs/{0}", id)) { Content = bytes };

            var response = _httpClient.SendAsync(request);

            try
            {
                var result = response.Result;
                var statusCode = result.StatusCode;
                if (statusCode == HttpStatusCode.Created)
                {
                    return;
                }

                RaiseResponseError(request, result);
            }
            finally
            {
                Dispose(request, response);
            }
        }
开发者ID:humblelistener,项目名称:pact-net,代码行数:26,代码来源:EventsApiClient.cs

示例4: ContentLength_UsePartialSourceArray_LengthMatchesArrayLength

        public void ContentLength_UsePartialSourceArray_LengthMatchesArrayLength()
        {
            var contentData = new byte[10];
            var content = new ByteArrayContent(contentData, 5, 3);

            Assert.Equal(3, content.Headers.ContentLength);
        }
开发者ID:ChuangYang,项目名称:corefx,代码行数:7,代码来源:ByteArrayContentTest.cs

示例5: ContentLength_UseWholeSourceArray_LengthMatchesArrayLength

        public void ContentLength_UseWholeSourceArray_LengthMatchesArrayLength()
        {
            var contentData = new byte[10];
            var content = new ByteArrayContent(contentData);

            Assert.Equal(contentData.Length, content.Headers.ContentLength);
        }
开发者ID:ChuangYang,项目名称:corefx,代码行数:7,代码来源:ByteArrayContentTest.cs

示例6: PostFile

        /// <summary>
        /// Create Multipart form-data HTTP Post to upload file to S3.
        /// </summary>
        /// <param name="s3Bucket">The Amazon S3 bucket name.</param>
        /// <param name="formData">The JSON object containing the pre-signed URL data.</param>
        /// <param name="mimeType">The MIME type of the file to be uploaded.</param>
        /// <param name="compressedFile">The gzipped file contents.</param>
        /// <returns>BlipResponse object with a status code and body text if applicable.</returns>
        private static BlipResponse PostFile(string s3Bucket, string formData, string mimeType, byte[] compressedFile)
        {
            HttpResponseMessage response;
            dynamic data = JsonConvert.DeserializeObject(formData);

            using (var client = new HttpClient())
            {
                var url = $"https://s3.amazonaws.com/{s3Bucket}";
                var requestContent = new MultipartFormDataContent();
                var fileContent = new ByteArrayContent(compressedFile);
                fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse(mimeType);
                
                // Special parsing required due to a hyphen in the key
                string contentMd5 = JObject.Parse(data.ToString())["content-md5"];

                requestContent.Add(new StringContent(data.acl.ToString()), "acl");
                requestContent.Add(new StringContent(data.bucket.ToString()), "bucket");
                requestContent.Add(new StringContent(data.key.ToString()), "key");
                requestContent.Add(new StringContent(contentMd5), "content-md5");
                requestContent.Add(new StringContent(data.policy.ToString()), "policy");
                requestContent.Add(new StringContent(data.signature.ToString()), "signature");
                requestContent.Add(new StringContent(data.AWSAccessKeyId.ToString()), "AWSAccessKeyId");
                requestContent.Add(new StringContent(mimeType), "content-type");
                requestContent.Add(fileContent, "file"); // The file must be added last
                
                response = client.PostAsync(url, requestContent).Result;
            }

            var statusCode = (int)response.StatusCode;

            // If the upload is not successful return the error message from S3 else return success response
            return statusCode != 204 ? new BlipResponse(statusCode, response.Content.ToString()) : new BlipResponse(statusCode, "");
        }
开发者ID:balihoo,项目名称:balihoo-blip-sdk-net,代码行数:41,代码来源:S3Request.cs

示例7: BuildMessage

        protected override HttpRequestMessage BuildMessage(IRestRequest request)
        {
            // Create message content
            var content = new MultipartFormDataContent();
            foreach (var param in request.Parameters) {
                var file = param.Value as FileParameter;

                if (file != null) {
                    var contentPart = new ByteArrayContent(file.Content);
                    contentPart.Headers.Add("Content-Type", file.ContentType);
                    content.Add(contentPart, param.Key, file.Name);
                }
                else {
                    var contentPart = new StringContent(param.Value.ToString());
                    content.Add(contentPart, param.Key);
                }
            }

            // Build message
            var message = new HttpRequestMessage(request.Verb.ToHttpMethod(), request.Command) {
                Content = content
            };

            return message;
        }
开发者ID:VeselovAndrey,项目名称:RestArt,代码行数:25,代码来源:MultipartFormDataMessageBuilder.cs

示例8: UploadBytes

        public async Task<bool> UploadBytes(string url, byte[] data)
        {
            try
            {
                if (_networkInformation.QuickNetworkCheck())
                {
                    var native = new NativeMessageHandler();

                    var httpClient = new HttpClient(native);
                    var message = new HttpRequestMessage(HttpMethod.Post, url);

                    native.RegisterForProgress(message, (bytes, totalBytes, expected) => new TransferProgressMessage(url, bytes, totalBytes, expected, true).Send());

                    var content = new ByteArrayContent(data);

                    message.Content = content;

                    var result = await httpClient.SendAsync(message);
                    return result.IsSuccessStatusCode;
                }
            }
            catch
            {
                Debug.WriteLine("WARNING: Could not upload: {0}", url);
            }

            return false;
        }
开发者ID:jakkaj,项目名称:Xamling-Core,代码行数:28,代码来源:iOSSimpleNativeHttpHttpTransfer.cs

示例9: 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

示例10: SendImageSet

        private static void SendImageSet(ImageSet imageSet)
        {
            var multipartContent = new MultipartFormDataContent();

            var imageSetJson = JsonConvert.SerializeObject(imageSet,
                new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                });

            multipartContent.Add(new StringContent(imageSetJson, Encoding.UTF8, "application/json"), "imageset");

            int counter = 0;
            foreach (var image in imageSet.Images)
            {
                var imageContent = new ByteArrayContent(image.ImageData);
                imageContent.Headers.ContentType = new MediaTypeHeaderValue(image.MimeType);
                multipartContent.Add(imageContent, "image" + counter++, image.FileName);
            }

            var response = new HttpClient()
                .PostAsync("http://localhost:53908/api/send", multipartContent)
                .Result;

            var responseContent = response.Content.ReadAsStringAsync().Result;
            Trace.Write(responseContent);
        }
开发者ID:santhosh2000k,项目名称:MultipartFormDataSample,代码行数:27,代码来源:Program.cs

示例11: 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

示例12: GetImage

        public async Task<HttpResponseMessage> GetImage(string name)
        {
            var userEmails = await UsersForHub();
            if (userEmails == null)
            {
                Services.Log.Error("No logged in user", null, "SetupToken");
                return new HttpResponseMessage(HttpStatusCode.Unauthorized);
            }

            byte[] imageBytes = null;
            foreach (var email in userEmails)
            {
                if (imageBytes == null)
                {
                    imageBytes = await GetStatusImageBytesForUser(email, name);
                }
            }

            if (imageBytes != null)
            {
                var content = new ByteArrayContent(imageBytes);
                content.Headers.ContentType = new MediaTypeHeaderValue("image/png");

                return new HttpResponseMessage(HttpStatusCode.OK) { Content = content };
            }
            else
            {
                Services.Log.Error(string.Format("Status image {0} not found", name));
                return new HttpResponseMessage(HttpStatusCode.NotFound);
            }
        }
开发者ID:Ogadai,项目名称:MyHomeSecureWeb,代码行数:31,代码来源:StatusImageController.cs

示例13: DoSyncRequest

 public ElasticsearchResponse DoSyncRequest(string method, Uri uri, byte[] data = null)
 {
     var client = new System.Net.Http.HttpClient();
     HttpResponseMessage response = null;
     byte[] result = null;
     HttpContent content = null;
     if (data != null)
         content = new ByteArrayContent(data);
     switch (method.ToLower())
     {
         case "head":
             response = client.SendAsync(new HttpRequestMessage(HttpMethod.Head, uri) ).Result;
             result = response.Content.ReadAsByteArrayAsync().Result;
             break;
         case "delete":
             response = client.SendAsync(new HttpRequestMessage(HttpMethod.Delete, uri) { Content = content }).Result;
             result = response.Content.ReadAsByteArrayAsync().Result;
             break;
         case "put":
             response = client.PutAsync(uri, content).Result;
             result = response.Content.ReadAsByteArrayAsync().Result;
             break;
         case "post":
             response = client.PostAsync(uri, content).Result;
             result = response.Content.ReadAsByteArrayAsync().Result;
             break;
         case "get":
             response = client.GetAsync(uri).Result;
             result = response.Content.ReadAsByteArrayAsync().Result;
             break;
     }
     return ElasticsearchResponse.Create(this._settings, (int)response.StatusCode, method, uri.ToString(), data, result);
 }
开发者ID:kowalot,项目名称:elasticsearch-net,代码行数:33,代码来源:ElasticsearchHttpClient.cs

示例14: CreatePageForIncidentAsync

        public async Task<string> CreatePageForIncidentAsync(string siteRootDirectory, string sectionId, Incident incident, IEnumerable<FileContent> inspectionPhotos, IEnumerable<Video> incidentVideos)
        {
            var templateFile = Path.Combine(siteRootDirectory, @"Templates\IncidentOneNotePage.cshtml");
            var template = System.IO.File.ReadAllText(templateFile);
            var viewBag = new RazorEngine.Templating.DynamicViewBag();
            viewBag.AddValue("InspectionPhotos", inspectionPhotos);
            viewBag.AddValue("IncidentVideos", incidentVideos);

            var html = RazorEngine.Engine.Razor.RunCompile(template, "IncidentOneNotePage", typeof(Incident), incident, viewBag);
            var content = new MultipartFormDataContent();
            content.Add(new StringContent(html, Encoding.UTF8, "text/html"), "Presentation");

            foreach (var image in inspectionPhotos)
            {
                var itemContent = new ByteArrayContent(image.Bytes);
                var contentType = MimeMapping.GetMimeMapping(image.Name);
                itemContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);
                content.Add(itemContent, image.Id);
            }

            this.pageEndPoint = string.Format("{0}/sections/{1}/pages", serviceBaseUrl, sectionId);
            var requestMessage = new HttpRequestMessage(HttpMethod.Post, pageEndPoint);
            requestMessage.Content = content;

            var responseMessage = await HttpSendAsync(requestMessage, accessToken);
            if (responseMessage.StatusCode != System.Net.HttpStatusCode.Created)
                throw new HttpResponseException(responseMessage.StatusCode);

            var reponseObject = await GetReponseObjectAsync(responseMessage);
            return (string)reponseObject.links.oneNoteWebUrl.href;
        }
开发者ID:modulexcite,项目名称:Property-Inspection-Code-Sample,代码行数:31,代码来源:OneNoteService.cs

示例15: UploadBytes

        public async Task<bool> UploadBytes(string url, byte[] data)
        {
            try
            {
                if (_networkInformation.QuickNetworkCheck())
                {
                    var h = new NativeMessageHandler();
                
                    var httpClient = new HttpClient(h);
                    var message = new HttpRequestMessage(HttpMethod.Post, url);

                    var content = new ByteArrayContent(data);

                    message.Content = content;

                    var result = await httpClient.SendAsync(message);
                    return result.IsSuccessStatusCode;
                }
            }
            catch
            {
                Debug.WriteLine("WARNING: Could not upload: {0}", url);
            }

            return false;
        }
开发者ID:jakkaj,项目名称:Xamling-Core,代码行数:26,代码来源:SimpleNativeHttpTransferer.cs


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