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"); } }
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; } }
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); } }
public async Task<ActionResult> Create(Area area, HttpPostedFileBase upload) { try { area.Id = Guid.NewGuid(); var formData = new MultipartFormDataContent(); var json = JsonConvert.SerializeObject(area); formData.Add(new StringContent(json, Encoding.Unicode, "application/json")); if (upload != null && upload.ContentLength > 0) { formData.Add(new StreamContent(upload.InputStream), upload.FileName, upload.FileName); } var response = await saguClient.PostAsync("api/areas", formData); if (response.IsSuccessStatusCode) { return RedirectToAction("Index"); } else return Content("An error occurred, status code " + response.ReasonPhrase); } catch { return Content("An error occurred."); } }
/// <exception cref="ArgumentNullException"></exception> internal HttpRequestMessage UploadImageBinaryRequest(string url, byte[] image, string album = null, string title = null, string description = null) { if (string.IsNullOrEmpty(url)) throw new ArgumentNullException(nameof(url)); if (image == null) throw new ArgumentNullException(nameof(image)); var request = new HttpRequestMessage(HttpMethod.Post, url); var content = new MultipartFormDataContent($"{DateTime.UtcNow.Ticks}") { {new StringContent("file"), "type"}, {new ByteArrayContent(image), nameof(image)} }; if (album != null) content.Add(new StringContent(album), nameof(album)); if (title != null) content.Add(new StringContent(title), nameof(title)); if (description != null) content.Add(new StringContent(description), nameof(description)); request.Content = content; return request; }
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; }
protected override void Send(ITask currentTask, string text, FileInfo logFile) { var mailSubject = text.Substring(0, text.IndexOf("\r\n")); var form = new MultipartFormDataContent(); form.Add(new StringContent(options.From), "from"); foreach (var to in options.To) { form.Add(new StringContent(to), "to"); } form.Add(new StringContent(mailSubject), "subject"); form.Add(new StringContent(text), "text"); if (logFile != null && logFile.Exists) { form.Add(new StreamContent(logFile.OpenRead()), "attachment", logFile.Name); } var credentials = new NetworkCredential("api", options.MailgunApiKey); var handler = new HttpClientHandler { Credentials = credentials }; using (var httpClient = new HttpClient(handler)) { httpClient.BaseAddress = new Uri(options.MailgunBaseUrl + options.MailgunDomain + "/"); var response = httpClient.PostAsync("messages", form).Result; response.EnsureSuccessStatusCode(); } }
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); }
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; }
public void GetStreamValidation() { Stream stream0 = null; Stream stream1 = null; try { MultipartFormDataContent content = new MultipartFormDataContent(); content.Add(new StringContent("Not a file"), "notafile"); content.Add(new StringContent("This is a file"), "file", "filename"); MultipartFileStreamProvider instance = new MultipartFileStreamProvider(Path.GetTempPath()); stream0 = instance.GetStream(content.ElementAt(0).Headers); Assert.IsType<FileStream>(stream0); stream1 = instance.GetStream(content.ElementAt(1).Headers); Assert.IsType<FileStream>(stream1); Assert.Equal(2, instance.BodyPartFileNames.Count); Assert.Contains("BodyPart", instance.BodyPartFileNames[0]); Assert.Contains("BodyPart", instance.BodyPartFileNames[1]); } finally { if (stream0 != null) { stream0.Close(); } if (stream1 != null) { stream1.Close(); } } }
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; }
/// <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; }
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; } }
public static async Task<ImgurEntity> UploadImgur(IRandomAccessStream fileStream) { try { var imageData = new byte[fileStream.Size]; for (int i = 0; i < imageData.Length; i++) { imageData[i] = (byte)fileStream.AsStreamForRead().ReadByte(); } var theAuthClient = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Post, "https://api.imgur.com/3/image"); request.Headers.Authorization = new AuthenticationHeaderValue("Client-ID", "e5c018ac1f4c157"); var form = new MultipartFormDataContent(); var t = new StreamContent(fileStream.AsStream()); // TODO: See if this is the correct way to use imgur's v3 api. I can't see why we would still need to convert images to base64. string base64Img = Convert.ToBase64String(imageData); t.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg"); form.Add(new StringContent(base64Img), @"image"); form.Add(new StringContent("file"), "type"); request.Content = form; HttpResponseMessage response = await theAuthClient.SendAsync(request); string responseString = await response.Content.ReadAsStringAsync(); if (responseString == null) return null; var imgurEntity = JsonConvert.DeserializeObject<ImgurEntity>(responseString); return imgurEntity; } catch (WebException) { } catch (IOException) { return null; } return null; }
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); } } } }
public CommentResult Create(string projectId, string taskId, string text, string filePath) { var message = new HttpRequestMessage(); var content = new MultipartFormDataContent(); content.Add(new StringContent(text ?? string.Empty), "Text"); if (!string.IsNullOrEmpty(filePath)) { var filestream = new FileStream(filePath, FileMode.Open); var fileName = System.IO.Path.GetFileName(filePath); content.Add(new StreamContent(filestream), "file", fileName); content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = fileName }; } message.Method = HttpMethod.Post; message.Content = content; message.RequestUri = new Uri(GetUrl(CommentActionUrls.New, projectId, taskId)); using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("Authorization-Token", token); var result = client.SendAsync(message).Result; ValidationCheck(result); return result.Content.ReadAsAsync<CommentResult>().Result; } }
public HttpContent ToPayload() { var content = new MultipartFormDataContent(); foreach (var p in GetBaseParameters()) { content.Add(new StringContent(p.Value), p.Key); } content.Add(new StreamContent(new MemoryStream(_video)), "video"); return content; }
public async Task<HttpResponseMessage> PostAsync(Uri uri, Dictionary<string, string> fields, string fileName, byte[] imageData) { ByteArrayContent file = new ByteArrayContent(imageData); MultipartFormDataContent form = new MultipartFormDataContent(); foreach (KeyValuePair<string, string> field in fields) form.Add(new StringContent(field.Value), "\"" + field.Key + "\""); form.Add(file, "\"upfile\"", "\"" + fileName + "\""); return await _client.PostAsync(EnforceHTTPS(uri), form); }
public override HttpContent ToPayload() { var content = new MultipartFormDataContent(); foreach (var p in GetBaseParameters()) { content.Add(new StringContent(p.Value), p.Key); } content.Add(new StreamContent(_stream), _name, _fileName); return content; }
//Perform the equivalent of posting a form with a filename and two files, in HTML: // <form action="{url}" method="post" enctype="multipart/form-data"> // <input type="file" name="file" /> // </form> public static bool Upload(string url, string privacy, string duration, string filename, Stream fileStream, byte[] fileBytes) { // Convert each of the three inputs into HttpContent objects HttpContent stringContent = new StringContent(filename); // examples of converting both Stream and byte [] to HttpContent objects // representing input type file HttpContent privacyContent = new StringContent(privacy); HttpContent durationContent = new StringContent(duration); HttpContent fileStreamContent = new StreamContent(fileStream); HttpContent bytesContent = new ByteArrayContent(fileBytes); // Submit the form using HttpClient and // create form data as Multipart (enctype="multipart/form-data") using (var client = new HttpClient()) using (var formData = new MultipartFormDataContent()) { client.DefaultRequestHeaders.Add("Authorization", "Basic Og=="); client.DefaultRequestHeaders.Add("token", Properties.Settings.Default.userToken); client.DefaultRequestHeaders.Add("cpt", Properties.Settings.Default.computerIdHashed); // Add the HttpContent objects to the form data formData.Add(privacyContent, "privacy"); formData.Add(durationContent, "duration"); formData.Add(fileStreamContent, "file", filename); // Actually invoke the request to the server // equivalent to (action="{url}" method="post") var response = client.PostAsync(url, formData).Result; JToken j = JToken.Parse(response.Content.ReadAsStringAsync().Result); switch((int)response.StatusCode) { case 200: string downloadLink = Api.EndpointRefs.downloadURL + j["data"]["downloadCode"]; Clipboard.SetText(downloadLink); MessageBox.Show("Upload successful. The following link has been copied to your clipboard." + "\n" + downloadLink); break; case 401: MessageBox.Show("You must log in to upload."); break; case 400: MessageBox.Show("Everything is broken."); break; } // equivalent of pressing the submit button on the form return response.IsSuccessStatusCode; } }
public async Task<string> UpdateWithMedia(string status, byte[] media, string fileName) { var client = OAuthUtility.CreateOAuthClient(_consumerKey, _consumerSecret, _accessToken); var content = new MultipartFormDataContent(); content.Add(new StringContent(status), "\"status\""); content.Add(new ByteArrayContent(media), "media[]", "\"" + fileName + "\""); var response = await client.PostAsync("https://upload.twitter.com/1/statuses/update_with_media.json", content); var json = await response.Content.ReadAsStringAsync(); return json; }
private void UploadDocument() { var putDocumentParams = new PutDocumentParams(long.Parse(txtDocumentTypeId.Text)); var compassNumberKWT = new KeywordType(136, "", typeof(string), ""); var ssnKWT = new KeywordType(103, "", typeof(string), ""); var firstNameKWT = new KeywordType(104, "", typeof(string), ""); var lastNameKWT = new KeywordType(105, "", typeof(string), ""); putDocumentParams.Keywords.Add(new Keyword(compassNumberKWT, txtCompassNumber.Text)); putDocumentParams.Keywords.Add(new Keyword(ssnKWT, txtSSN.Text)); putDocumentParams.Keywords.Add(new Keyword(firstNameKWT, txtFirstName.Text)); putDocumentParams.Keywords.Add(new Keyword(lastNameKWT, txtLastName.Text)); var multipartContent = new MultipartFormDataContent(); var searlizedPutDocumentMetadata = JsonConvert.SerializeObject(putDocumentParams, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); multipartContent.Add(new StringContent(searlizedPutDocumentMetadata, Encoding.UTF8, "application/json"), "PutDocumentParams"); var sw = new Stopwatch(); sw.Start(); var counter = 1; foreach (var fileName in Directory.GetFiles(txtImagesFolderPath.Text)) { var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); multipartContent.Add(new StreamContent(fs), "File" + counter, Path.GetFileName(fileName)); counter++; } try { using (var response = new HttpClient().PostAsync("http://localhost/CompassDataBroker/api/Document/UploadFile", multipartContent).Result) { var responseContent = response.Content.ReadAsStringAsync().Result; sw.Stop(); MessageBox.Show(String.Format("Document Id: {0} \nCompleted in {1} seconds", responseContent, sw.Elapsed.TotalSeconds)); Trace.Write(responseContent); } } catch (Exception ex) { sw.Stop(); throw; } }
//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; }
public static void Test1() { string fileName = "op_1_front.jpg"; System.Drawing.Image imgFile = System.Drawing.Image.FromFile(fileName); var imageSet = new ImageSet() { Name = "op_1", }; var image = new Image() { FileName = fileName, MimeType = "image/jpeg", Side = SideEnum.Front, ImageData = imgFile.ToArray(System.Drawing.Imaging.ImageFormat.Jpeg), }; imageSet.Images.Add(image); 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 img in imageSet.Images) { var imageContent = new ByteArrayContent(img.ImageData); imageContent.Headers.ContentType = new MediaTypeHeaderValue(img.MimeType); imageContent.Headers.Add("Side", img.Side.ToString()); multipartContent.Add(imageContent, "image" + counter++, img.FileName); } string url = "http://93.153.125.236/Impresto.Ocr/api/recognize"; //string url = "http://localhost:65000/api/recognize"; var response = new HttpClient() .PostAsync(url, multipartContent) .Result; var responseContent = response.Content.ReadAsStringAsync().Result; Console.WriteLine(responseContent); }
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); }
public async Task <string> UploadFirmware(string fileName, Stream binFile) { CameraInfo.UpdatingFirmware = true; try { string requestStr = String.Format("http://{0}/upgrade_firmware.cgi", CameraInfo.IpAddress); var fileContents = new System.Net.Http.StreamContent(binFile); fileContents.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream"); var content = new System.Net.Http.MultipartFormDataContent("---------------------------7deef381d07b6"); content.Add(fileContents, "file", fileName); // override the content disposition var contentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data"); contentDisposition.Name = "file"; contentDisposition.FileName = fileName; fileContents.Headers.ContentDisposition = contentDisposition; return(await PostFormRequest(requestStr, content)); } finally { // actually, let's wait for next ping to succeed which means the reboot is finished. // CameraInfo.UpdatingFirmware = false; } }
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); }
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; } } } }
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; } }
public static byte[] PostMultipartFormDataBodyReturnBytes(string url, IDictionary <string, object> values, Encoding encoding = null, IDictionary <string, string> headers = null, string referrer = null, string accept = null) { var content = new System.Net.Http.MultipartFormDataContent(); encoding = encoding ?? Encoding.UTF8; foreach (var item in values) { if (item.Value == null) { throw new Exception("参数的值为NULL"); } else if (item.Value is byte) { var cc = new System.Net.Http.StreamContent(new MemoryStream((byte[])item.Value)); cc.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg"); content.Add(cc, item.Key, item.Key); } else if (item.Value is string) { content.Add(new System.Net.Http.StringContent(item.Value as string, encoding ?? Encoding.UTF8, "application/x-www-form-urlencoded"), item.Key); } else { throw new Exception("不支持的类型:" + item.Value.GetType().FullName); } } var client = SetupClient(headers, referrer, accept); HttpResponseMessage ret = null; try { ret = client.PostAsync(url, content).Result; } catch (Exception ex) { throw GetOrignalException(ex); } if (ret.IsSuccessStatusCode == false) { throw new Exception("HTTP请求错误:" + ret.StatusCode); } var data = ret.Content.ReadAsByteArrayAsync().Result; return(data); }
internal override void WriteContent(HttpRequestMessage request) { var content = new System.Net.Http.MultipartFormDataContent(); foreach (var item in _contents) { if (item.Value is string s) { content.Add(new System.Net.Http.StringContent(s, Encoding.UTF8), item.Key); } else if (item.Value is FileContent file) { content.Add(new StreamContent(file.Steam), item.Key, file.FileName ?? item.Key); } } request.Content = content; }
public static byte[] PostMultipartFormDataBodyReturnBytes(string url, IDictionary <string, object> values, IList <string> fileNames, Encoding encoding = null, IDictionary <string, string> headers = null, string referrer = null, string accept = null) { var content = new System.Net.Http.MultipartFormDataContent(); if (encoding == null) { encoding = Encoding.UTF8; } int i = 0; foreach (var item in values) { if (item.Value == null) { content.Add(new System.Net.Http.StringContent(""), item.Key); } else if (item.Value.GetType() == typeof(byte[])) { var cc = new System.Net.Http.StreamContent(new MemoryStream((byte[])item.Value)); cc.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg"); content.Add(cc, item.Key, fileNames[i]); i++; } else if (item.Value.GetType() == typeof(DateTime)) { content.Add(new System.Net.Http.StringContent(((DateTime)item.Value).ToString("yyyy-MM-dd HH:mm:ss")), item.Key); } else if (item.Value is Enum) { content.Add(new System.Net.Http.StringContent(((int)item.Value).ToString()), item.Key); } else if (item.Value is double) { content.Add(new System.Net.Http.StringContent(((double)item.Value).ToString("F2")), item.Key); } else if (item.Value is float) { content.Add(new System.Net.Http.StringContent(((float)item.Value).ToString("F2")), item.Key); } else { content.Add(new System.Net.Http.StringContent(item.Value.ToString()), item.Key); } } var client = SetupClient(headers, referrer, accept); var ret = client.PostAsync(url, content).Result; if (ret.IsSuccessStatusCode == false) { throw new Exception("HTTP请求错误:" + ret.StatusCode); } var data = ret.Content.ReadAsByteArrayAsync().Result; return(data); }
public Result UploadFile(string pathFile, Stream stream) { var result = new Result(); var content = new System.Net.Http.MultipartFormDataContent(); content.Add(new System.Net.Http.StreamContent(stream)); var msg = hc.PostAsync(pathFile, content).Result.Content.ReadAsStringAsync().Result; if (!msg.Contains("error")) { result.Status = true; } return(result); }
public async Task <UploadPhotoResult> UploadPhoto(string url, string folderPhotoPath, byte[] photo) { HttpClient client = new HttpClient(); MultipartContent content = new System.Net.Http.MultipartFormDataContent(); var photoFile = new ByteArrayContent(photo); photoFile.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "photo", FileName = folderPhotoPath + "result.jpg", }; content.Add(photoFile); HttpResponseMessage response = await client.PostAsync(url, content); response.EnsureSuccessStatusCode(); var responseBody = await response.Content.ReadAsStringAsync(); return(JsonConvert.DeserializeObject <UploadPhotoResult>(responseBody)); }
public static async Task findPerson() {/* * var url = $"http://192.168.15.27:8090/person/find"; * HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); * request.Method = "POST"; * request.Credentials = CredentialCache.DefaultCredentials; * request.ContentType = "application/form-data"; * request.Accept = "application/json"; */ try { string baseUrl = "/person/find"; var parameters = new Dictionary <string, string>(); parameters.Add("pass", "87654321"); parameters.Add("id", "3"); System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); client.BaseAddress = new Uri("http://192.168.15.27:8090" + baseUrl); System.Net.Http.MultipartFormDataContent form = new System.Net.Http.MultipartFormDataContent(); HttpContent DictionaryItems = new FormUrlEncodedContent((IEnumerable <KeyValuePair <string, string> >)parameters); form.Add(DictionaryItems, "personFind"); var response = await client.PostAsync("/person/find", form); var k = await response.Content.ReadAsStringAsync(); Console.WriteLine(response); Console.ReadKey(); } catch (Exception e) { } }
public async void PostProcessing_ProcessesFormData_WithCustomMultipartFormDataStreamProvider() { // Arrange string tempPath = Path.GetTempPath(); int maxContents = 16; string contentFormat = "Content {0}"; string formNameFormat = "FormName_{0}"; string fileNameFormat = "FileName_{0}"; MultipartFormDataContent multipartContent = new MultipartFormDataContent(); // Create half contents for form data and the other half for file data. for (int index = 0; index < maxContents; index++) { string content = String.Format(contentFormat, index); string formName = String.Format(formNameFormat, index); if (index < maxContents / 2) { multipartContent.Add(new StringContent(content), formName); } else { string fileName = String.Format(fileNameFormat, index); multipartContent.Add(new StringContent(content), formName, fileName); } } CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(tempPath); foreach (HttpContent content in multipartContent) { provider.Contents.Add(content); using (provider.GetStream(multipartContent, content.Headers)) { } } // Act Task processingTask = provider.ExecutePostProcessingAsync(); await processingTask; // Assert Assert.Equal(TaskStatus.RanToCompletion, processingTask.Status); Assert.Equal(maxContents / 2, provider.FormData.Count); // half contents for form data for (int index = 0; index < maxContents / 2; index++) { string content = String.Format(contentFormat, index); string formName = String.Format(formNameFormat, index); Assert.Equal(content, provider.FormData[formName]); } // the other half for file data HttpContent[] contents = multipartContent.ToArray(); for (int index = maxContents / 2; index < maxContents; index++) { int fileDataIndex = index - (maxContents / 2); string fileName = String.Format(fileNameFormat, index); Assert.Equal(fileName, provider.FileData[fileDataIndex].LocalFileName); Assert.Same(contents[index].Headers, provider.FileData[fileDataIndex].Headers); } }
private IHttpResult RequestAccessToken(IServiceBase authService, IAuthSession session, string code, IAuthTokens tokens) { try { //JsonObject json = new JsonObject(); //json["grant_type"] = "authorization_code"; //json["client_id"] = ClientId; //json["scope"] = Scopes.Join(" ").UrlEncode(); //json["code"] = code; //json["redirect_uri"] = CallbackUrl.UrlEncode(); //json["client_secret"] = ClientSecret; // using (var handler = new HttpClientHandler { Proxy = new WebProxy("127.0.0.1:8888", false) }) // { var content = new System.Net.Http.MultipartFormDataContent(); content.Add(new System.Net.Http.StringContent("authorization_code"), "grant_type"); content.Add(new System.Net.Http.StringContent(ClientId), "client_id"); content.Add(new System.Net.Http.StringContent("openid"), "scope"); content.Add(new System.Net.Http.StringContent(code), "id_token"); content.Add(new System.Net.Http.StringContent(CallbackUrl), "redirect_uri"); content.Add(new System.Net.Http.StringContent(ClientSecret), "client_secret"); HttpClient httpClient = new HttpClient(); HttpResponseMessage response = null; string responseJson = null; // run some async code inside a non-async method Task.Run(async() => { response = await httpClient.PostAsync(AccessTokenUrl, content); responseJson = await response.Content.ReadAsStringAsync(); }).GetAwaiter().GetResult(); // tokens. = authInfo["access_token"]; // var formData = "client_id={0}&redirect_uri={1}&client_secret={2}&code={3}&grant_type=authorization_code&resource={4}&scope={5}" // .Fmt(ClientId.UrlEncode(), CallbackUrl.UrlEncode(), ClientSecret.UrlEncode(), code, ResourceId.UrlEncode(), Scopes.Join(" ")); // Endpoint only accepts posts requests // var contents = AccessTokenUrl.PostToUrl(formData); // var contents = AccessTokenUrl.PostJsonToUrl(json.ToString()); // 4. The Azure AD token issuance endpoint returns an access token // and a refresh token. The refresh token can be used to request // additional access tokens. // Response is JSON var authInfo = JsonObject.Parse(responseJson); var authInfoNvc = authInfo.ToNameValueCollection(); if (HasError(authInfoNvc)) { return(RedirectDueToFailure(authService, session, authInfoNvc)); } tokens.AccessTokenSecret = authInfo["access_token"]; tokens.RefreshToken = authInfo["refresh_token"]; tokens.AccessToken = authInfo["id_token"]; return(OnAuthenticated(authService, session, tokens, authInfo.ToDictionary()) ?? authService.Redirect(SuccessRedirectUrlFilter(this, session.ReferrerUrl.SetParam("s", "1")))); //Haz Access! //} } catch (WebException webException) { if (webException.Response == null) { // This could happen e.g. due to a timeout return(RedirectDueToFailure(authService, session, new NameValueCollection { { "error", webException.GetType().ToString() }, { "error_description", webException.Message } })); } Log.Error("Auth Failure", webException); var response = ((HttpWebResponse)webException.Response); var responseText = Encoding.UTF8.GetString( response.GetResponseStream().ReadFully()); var errorInfo = JsonObject.Parse(responseText).ToNameValueCollection(); return(RedirectDueToFailure(authService, session, errorInfo)); } //return RedirectDueToFailure(authService, session, new NameValueCollection()); }
public void sendRequest( string method, Uri url, int requestId, string[][] headers, JObject data, string responseType, bool useIncrementalUpdates, int timeout) { if (method == null) { throw new ArgumentNullException(nameof(method)); } if (url == null) { throw new ArgumentNullException(nameof(url)); } if (responseType == null) { throw new ArgumentNullException(nameof(responseType)); } if (responseType != "text" && responseType != "base64") { throw new ArgumentOutOfRangeException(nameof(responseType)); } var request = new HttpRequestMessage(new HttpMethod(method), url); var headerData = default(HttpContentHeaderData); if (headers != null) { headerData = HttpContentHelpers.ExtractHeaders(headers); ApplyHeaders(request, headers); } if (data != null) { var body = data.Value <string>("string"); var uri = default(string); var formData = default(JArray); if (body != null) { if (headerData.ContentType == null) { OnRequestError(requestId, "Payload is set but no 'content-type' header specified.", false); return; } request.Content = HttpContentHelpers.CreateFromBody(headerData, body); } else if ((uri = data.Value <string>("uri")) != null) { if (headerData.ContentType == null) { OnRequestError(requestId, "Payload is set but no 'content-type' header specified.", false); return; } _tasks.AddAndInvokeAsync(requestId, token => ProcessRequestFromUriAsync( requestId, new Uri(uri), useIncrementalUpdates, timeout, request, responseType, token)); return; } else if ((formData = (JArray)data.GetValue("formData", StringComparison.Ordinal)) != null) { if (headerData.ContentType == null) { headerData.ContentType = "multipart/form-data"; } var formDataContent = new HttpMultipartFormDataContent(); foreach (var content in formData) { var fieldName = content.Value <string>("fieldName"); var stringContent = content.Value <string>("string"); if (stringContent != null) { formDataContent.Add(new HttpStringContent(stringContent), fieldName); } } request.Content = formDataContent; } } _tasks.AddAndInvokeAsync(requestId, async token => { using (request) { try { await ProcessRequestAsync( requestId, useIncrementalUpdates, timeout, request, responseType, token); } finally { var content = request.Content; if (content != null) { content.Dispose(); } } } }); }
/// <summary>Download converted file from the job</summary> /// <param name="filename">Filename</param> /// <param name="jobId">Job Id</param> /// <returns>Success</returns> /// <exception cref="SwaggerException">A server side error occurred.</exception> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> public async System.Threading.Tasks.Task <FileResponse> DownloadJobFileResultAsync(string filename, string jobId, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/DownloadJobFileResult"); var client_ = _httpClient; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var boundary_ = System.Guid.NewGuid().ToString(); var content_ = new System.Net.Http.MultipartFormDataContent(boundary_); content_.Headers.Remove("Content-Type"); content_.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary_); if (filename != null) { content_.Add(new System.Net.Http.StringContent(ConvertToString(filename, System.Globalization.CultureInfo.InvariantCulture)), "filename"); } if (jobId != null) { content_.Add(new System.Net.Http.StringContent(ConvertToString(jobId, System.Globalization.CultureInfo.InvariantCulture)), "jobId"); } request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/octet-stream")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200" || status_ == "206") { var responseStream_ = response_.Content == null ? System.IO.Stream.Null : await response_.Content.ReadAsStreamAsync().ConfigureAwait(false); var fileResponse_ = new FileResponse((int)response_.StatusCode, headers_, responseStream_, null, response_); client_ = null; response_ = null; // response and client are disposed by FileResponse return(fileResponse_); } else if (status_ != "200" && status_ != "204") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null); } return(default(FileResponse)); } finally { if (response_ != null) { response_.Dispose(); } } } } finally { } }
/// <summary>Upload a new Job</summary> /// <param name="file">Input File</param> /// <param name="fScriptParams">Parameters for the script</param> /// <param name="scriptFilename">Script to use</param> /// <param name="outputFileFormat">format of the file output</param> /// <returns>Success</returns> /// <exception cref="SwaggerException">A server side error occurred.</exception> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> public async System.Threading.Tasks.Task <JobResult> UploadJobAsync(FileParameter file, string fScriptParams, string scriptFilename, string outputFileFormat, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/UploadJob"); var client_ = _httpClient; try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var boundary_ = System.Guid.NewGuid().ToString(); var content_ = new System.Net.Http.MultipartFormDataContent(boundary_); content_.Headers.Remove("Content-Type"); content_.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary_); if (file != null) { var content_file_ = new System.Net.Http.StreamContent(file.Data); if (!string.IsNullOrEmpty(file.ContentType)) { content_file_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(file.ContentType); } content_.Add(content_file_, "file", file.FileName ?? "file"); } if (fScriptParams != null) { content_.Add(new System.Net.Http.StringContent(ConvertToString(fScriptParams, System.Globalization.CultureInfo.InvariantCulture)), "fScriptParams"); } if (scriptFilename != null) { content_.Add(new System.Net.Http.StringContent(ConvertToString(scriptFilename, System.Globalization.CultureInfo.InvariantCulture)), "scriptFilename"); } if (outputFileFormat != null) { content_.Add(new System.Net.Http.StringContent(ConvertToString(outputFileFormat, System.Globalization.CultureInfo.InvariantCulture)), "outputFileFormat"); } request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(System.Net.Http.Headers.MediaTypeWithQualityHeaderValue.Parse("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) { headers_[item_.Key] = item_.Value; } } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); var result_ = default(JobResult); try { result_ = Newtonsoft.Json.JsonConvert.DeserializeObject <JobResult>(responseData_, _settings.Value); return(result_); } catch (System.Exception exception_) { throw new SwaggerException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_); } } else if (status_ != "200" && status_ != "204") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null); } return(default(JobResult)); } finally { if (response_ != null) { response_.Dispose(); } } } } finally { } }
public MediaPage() { InitializeComponent(); takePhoto.Clicked += async(sender, args) => { if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported) { DisplayAlert("No Camera", ":( No camera available.", "OK"); return; } var file = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.StoreCameraMediaOptions { Directory = "Test", SaveToAlbum = true, CompressionQuality = 75, CustomPhotoSize = 50, PhotoSize = PhotoSize.MaxWidthHeight, MaxWidthHeight = 2000, DefaultCamera = CameraDevice.Front }); if (file == null) { return; } DisplayAlert("File Location", file.Path, "OK"); image.Source = ImageSource.FromStream(() => { stream = file.GetStream(); file.Dispose(); return(stream); }); }; pickPhoto.Clicked += async(sender, args) => { if (!CrossMedia.Current.IsPickPhotoSupported) { DisplayAlert("Photos Not Supported", ":( Permission not granted to photos.", "OK"); return; } var file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions { PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium, }); if (file == null) { return; } image.Source = ImageSource.FromStream(() => { stream = file.GetStream(); file.Dispose(); return(stream); }); }; takeVideo.Clicked += async(sender, args) => { if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakeVideoSupported) { DisplayAlert("No Camera", ":( No camera avaialble.", "OK"); return; } var file = await CrossMedia.Current.TakeVideoAsync(new Plugin.Media.Abstractions.StoreVideoOptions { Name = "video.mp4", Directory = "DefaultVideos", }); if (file == null) { return; } DisplayAlert("Video Recorded", "Location: " + file.Path, "OK"); file.Dispose(); }; pickVideo.Clicked += async(sender, args) => { if (!CrossMedia.Current.IsPickVideoSupported) { DisplayAlert("Videos Not Supported", ":( Permission not granted to videos.", "OK"); return; } var file = await CrossMedia.Current.PickVideoAsync(); if (file == null) { return; } DisplayAlert("Video Selected", "Location: " + file.Path, "OK"); file.Dispose(); }; sendfile.Clicked += async(sender, args) => { //todo put other your IIS s try { if (stream == null) { return; // user canceled file picking } using (HttpClient _httpClient = new HttpClient()) { var url = "https://localhost:44360/api/FileApi/save"; var boundary = System.Guid.NewGuid().ToString(); var content = new System.Net.Http.MultipartFormDataContent(boundary); content.Headers.Remove("Content-Type"); content.Headers.TryAddWithoutValidation("Content-Type", "multipart/form-data; boundary=" + boundary); content.Add(new System.Net.Http.StreamContent(stream)); await _httpClient.PostAsync(url, content); } } catch (Exception ex) { var exception = ex; DisplayAlert("Video Selected", "Location: " + ex.Message, "OK"); } }; }
/// <summary> /// Upload file /// </summary> /// <param name='fileContent'> /// File to upload. /// </param> /// <param name='fileName'> /// File name to upload. Name has to be spelled exactly as written here. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <Stream> > UploadFileWithHttpMessagesAsync(Stream fileContent, string fileName, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (fileContent == null) { throw new ValidationException(ValidationRules.CannotBeNull, "fileContent"); } if (fileName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "fileName"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("fileContent", fileContent); tracingParameters.Add("fileName", fileName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "UploadFile", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "formdata/stream/uploadfile").ToString(); // Create HTTP transport objects var _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; System.Net.Http.MultipartFormDataContent _multiPartContent = new System.Net.Http.MultipartFormDataContent(); if (fileContent != null) { System.Net.Http.StreamContent _fileContent = new System.Net.Http.StreamContent(fileContent); _fileContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream"); FileStream _fileContentAsFileStream = fileContent as FileStream; if (_fileContentAsFileStream != null) { System.Net.Http.Headers.ContentDispositionHeaderValue _contentDispositionHeaderValue = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data"); _contentDispositionHeaderValue.Name = "fileContent"; _contentDispositionHeaderValue.FileName = _fileContentAsFileStream.Name; _fileContent.Headers.ContentDisposition = _contentDispositionHeaderValue; } _multiPartContent.Add(_fileContent, "fileContent"); } if (fileName != null) { System.Net.Http.StringContent _fileName = new System.Net.Http.StringContent(fileName, System.Text.Encoding.UTF8); _multiPartContent.Add(_fileName, "fileName"); } _httpRequest.Content = _multiPartContent; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <Error>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse <Stream>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _result.Body = await _httpResponse.Content.ReadAsStreamAsync().ConfigureAwait(false); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
//TODO: Update response object public static async Task<Upload> media_upload(this Api api, string media_data = "", byte[] media = null, 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(); if (!string.IsNullOrEmpty(media_data)) content.Add(new StringContent(media_data)); if (media != null) content.Add(new ByteArrayContent(media)); if (additional_owners != null && additional_owners.Any()) { content.Add(new StringContent(string.Join(",", 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; }
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(); } } }