public async Task <string> CreateEvent(string eventFile) { try { using (HttpClient client = new HttpClient()) { using (var content = new MultipartFormDataContent()) { using (var file = File.OpenRead(eventFile)) { using (var streamContent = new StreamContent(file)) { using (var fileContent = new ByteArrayContent(await streamContent.ReadAsByteArrayAsync())) { fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); content.Add(fileContent, "file", Path.GetFileName(eventFile)); HttpResponseMessage response = await client.PostAsync(_url, content); string responseMessage = await response.Content.ReadAsAsync <string>(); return(responseMessage); } } } } } } catch (Exception ex) { return("Upload Event error: " + ex.Message); } }
public async Task <Object> UploadFileServer([FromBody] CustomModel data) { using (var httpClient = new HttpClient()) { using (var form = new MultipartFormDataContent()) { using (var fs = System.IO.File.OpenRead(data.filepath)) { using (var streamContent = new StreamContent(fs)) { using (var fileContent = new ByteArrayContent(await streamContent.ReadAsByteArrayAsync())) { //fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); // "file" parameter name should be the same as the server side input parameter name form.Add(fileContent, "file", Path.GetFileName(data.filepath)); httpClient.DefaultRequestHeaders.Add("x-oc-api-key", "744be7d281d6b3b6871baef24cf58052"); HttpResponseMessage response = await httpClient.PostAsync(data.server, form); var strResponse = await response.Content.ReadAsStringAsync(); return(JsonConvert.DeserializeObject <UploadedFile>(strResponse)); /*return rootId.id.job;*/ } } } } } }
public async Task <IActionResult> ExtractFaceMetrics(IFormFile file) { // full path to file in temp location //var imageFilePath = Path.GetTempFileName(); //var imageByteArray = Utilities.GetImageAsByteArray(imageFilePath); string requestParameters = "returnFaceId=false&returnFaceLandmarks=false&returnFaceAttributes=Smile&recognitionModel=recognition_01"; // Assemble the URI for the REST API Call. string uri = uriBase + "?" + requestParameters; string result = null; using (var client = new HttpClient()) { client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey); HttpContent content = new StreamContent(file.OpenReadStream()); content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); var imageByteArray = await content.ReadAsByteArrayAsync(); // serialize the http content to a byte array //var response = await client.PostAsync(uri, content); var response = await client.PostAsync(uri, content); result = await response.Content.ReadAsStringAsync(); result += "\n Image bytearray: \n" + imageByteArray.Length; } return(Ok(result)); }
public async Task <bool> Upload(string fileName) { using (var form = new MultipartFormDataContent()) { using (var fs = File.OpenRead(fileName)) { using (var streamContent = new StreamContent(fs)) { using (var fileContent = new ByteArrayContent(await streamContent.ReadAsByteArrayAsync())) { fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); form.Add(fileContent, "file", Path.GetFileName(fileName)); HttpResponseMessage response = await client.PostAsync($"{baseUrl}{fileServiceName}", form); if (!response.IsSuccessStatusCode) { return(false); } } } } } return(true); }
public async Task <ActionResult> /*Task<ActionResult>*/ AddDog(DogModel addedDog, HttpPostedFileBase imageFile) { if (!LoginHelper.IsAuthenticated()) { return(RedirectToAction("Login", "Account", new { returnUrl = this.Request.Url.AbsoluteUri })); } if (imageFile != null) { MultipartFormDataContent form = new MultipartFormDataContent(); var imageStreamContent = new StreamContent(imageFile.InputStream); var byteArrayImageContent = new ByteArrayContent(imageStreamContent.ReadAsByteArrayAsync().Result); byteArrayImageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); var imageFileName = imageFile.FileName + Guid.NewGuid().ToString(); form.Add(byteArrayImageContent, imageFileName, Path.GetFileName(imageFileName)); var response = client.PostAsync("Dogs/Upload", form).Result; if (response.IsSuccessStatusCode) { //get blob urls - is it that simple or it has to be returned? var imageBlobUrl = @"https://kgtstorage.blob.core.windows.net/images/" + imageFileName; //add blob urls to model addedDog.PhotoBlobUrl = imageBlobUrl; } else { ViewBag.Message = response.StatusCode; return(View("Error")); } } client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", LoginHelper.GetToken()); HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress + "dogs/"); addedDog.DateOfBirth = addedDog.DateOfBirth.ToUniversalTime(); var dogSerialized = JsonConvert.SerializeObject(addedDog); message.Content = new StringContent(dogSerialized, System.Text.Encoding.UTF8, "application/json"); HttpResponseMessage responseMessage = client.SendAsync(message).Result; // await client.SendAsync(message) if (responseMessage.IsSuccessStatusCode) //200 OK { //display info message.Dispose(); return(RedirectToAction("Dog", new { id = Int32.Parse(responseMessage.Content.ReadAsStringAsync().Result) })); //return View("Dog", responseMessage.Content); } else // msg why not ok { message.Dispose(); ViewBag.Message = responseMessage.StatusCode; return(View("Error")); } }
public async Task <ActionResult> Uploadfile(int contextId, string option, bool edit) { try { var content = new StreamContent(HttpContext.Request.Body); byte[] recievingImage = await content.ReadAsByteArrayAsync(); System.Diagnostics.Debug.WriteLine(recievingImage.Length); if (edit) { imagesTableController.EditImage(option, contextId, recievingImage); } else { imagesTableController.AddImage(imagesTableController.NewImage(recievingImage, contextId, option)); } return(Ok()); } catch (Exception e) { System.Diagnostics.Debug.WriteLine("CUSTOM ERROR:"); System.Diagnostics.Debug.WriteLine(e.Message); return(NotFound()); } }
static void Main(string[] args) { Console.WriteLine("Hello World!"); Console.ReadLine(); for (int i = 0; i < treadsCount; i++) { var path = @"C:\Users\andrey.zaitsev\Pictures\500_F_135722246_wbxhr1Q4yxVW5foaDZHkwSLjYl8wbJAO.jpg"; ThreadPool.SetMinThreads(treadsCount, treadsCount); var url = "http://*****:*****@"C:\Users\andrey.zaitsev\Pictures\500_F_135722246_wbxhr1Q4yxVW5foaDZHkwSLjYl8wbJAO.jpg"; HttpClient httpClient = new HttpClient(); MultipartFormDataContent form = new MultipartFormDataContent(); FileStream fs = File.OpenRead(filePath); var streamContent = new StreamContent(fs); var imageContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result); imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart /form-data"); form.Add(imageContent, "image", i + ".jpg"); var response = httpClient.PostAsync(url, form).Result; } }
public async Task <HttpResponseMessage> UploadFile(string bucket, string filePath, IDictionary <string, object> metadata = null) { if (!File.Exists(filePath)) { throw new FileNotFoundException(filePath); } var requestContent = new MultipartFormDataContent(); metadata?.Keys.ToList().ForEach(key => { if (metadata[key] is string || metadata[key] is Guid) { requestContent.Add(new StringContent(metadata[key].ToString()), key); } else { requestContent.Add(new StringContent(JsonConvert.SerializeObject(metadata[key])), key); } }); StreamContent streamContent = new StreamContent(File.OpenRead(filePath)); var fileContent = new ByteArrayContent(await streamContent.ReadAsByteArrayAsync()); fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream"); requestContent.Add(fileContent, "File", Path.GetFileName(filePath)); return(await PostAsync(new Uri(BaseUri, bucket), requestContent)); }
public async static Task <CachedHttpResponse> From(HttpRequestMessage request, HttpResponseMessage response) { var cached = new CachedHttpResponse { RequestUri = request.RequestUri , Method = request.Method.ToString() , StatusCode = response.StatusCode , ReasonPhrase = response.ReasonPhrase }; if (response.Content != null) { using var ms = new MemoryStream(); await response.Content.CopyToAsync(ms); ms.Position = 0; using var sr = new StreamContent(ms); cached.Content = await sr.ReadAsByteArrayAsync(); ms.Seek(0, SeekOrigin.Begin); } foreach (var header in response.Headers) { cached.Headers.TryAdd(header.Key, header.Value.ToList()); } foreach (var header in response.Content?.Headers) { cached.ContentHeaders.TryAdd(header.Key, header.Value.ToList()); } return(cached); }
private void RegistrarContentsParaMultiPartForm(Peca peca, MultipartFormDataContent form) { if (!(string.IsNullOrEmpty(peca.CaminhoImagem) || peca.CaminhoImagem.StartsWith("http"))) { peca.CaminhoImagem = DependencyService.Get <IFotoLoadMediaPlugin>().GetPathToPhoto(peca.CaminhoImagem); var fileStream = new FileStream(peca.CaminhoImagem, FileMode.Open); var streamContent = new StreamContent(fileStream); var imagemContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result); imagemContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); form.Add(imagemContent, "arquivo", Path.GetFileName(peca.CaminhoImagem)); var caminhoImagemContent = new StringContent(peca.CaminhoImagem); caminhoImagemContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); form.Add(caminhoImagemContent, "caminhoImagem"); } var pecaIDContent = new StringContent(peca.PecaID.ToString()); pecaIDContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); form.Add(pecaIDContent, "pecaID"); Debug.WriteLine(peca.PecaID); var nomeContent = new StringContent(peca.Nome); nomeContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); form.Add(nomeContent, "nome"); var valorContent = new StringContent(string.Format("{0:N}", peca.Valor).Replace(',', '.')); valorContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); form.Add(valorContent, "valor"); }
public async Task Will_upload_a_valid_pdf() { using (var host = await GenericCreateAndStartHost_GetTestServer()) { var filePath = GetFilePath("sample_150kB.pdf"); using var multipartFormDataContent = new MultipartFormDataContent(); using var fs = File.OpenRead(filePath); using var streamContent = new StreamContent(fs); using var fileContent = new ByteArrayContent(await streamContent.ReadAsByteArrayAsync()); fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/pdf"); // "file" parameter name should be the same as the server side input parameter name multipartFormDataContent.Add(fileContent, "file", Path.GetFileName(filePath)); var response = await host.GetTestServer().CreateClient() .PostAsync("/api/v1/document/upload", multipartFormDataContent); Assert.Equal(HttpStatusCode.Created, response.StatusCode); var absoluteUri = response.Headers?.Location?.AbsoluteUri; Assert.True(!string.IsNullOrWhiteSpace(absoluteUri)); //todo: teardown } }
public async Task <StorageServiceFileDto> SaveFileAsync(string fileName, byte[] fileContents) { using (var form = new MultipartFormDataContent()) { using (var memoryStream = new MemoryStream(fileContents)) { using (var streamContent = new StreamContent(memoryStream)) { // TODO: remove ReadAsByteArrayAsync() var content = await streamContent.ReadAsByteArrayAsync(); using (var fileContent = new ByteArrayContent(content)) { fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); form.Add(fileContent, "file", fileName); var response = await _httpClient.PostAsync(_url, form); if (response.StatusCode != HttpStatusCode.Created) { throw new Exception($"Error during uploading {fileName}."); } var responseContent = await response.Content.ReadAsStringAsync(); var deserialized = JsonConvert.DeserializeObject <StorageServiceFileDto>(responseContent); return(deserialized); } } } } }
public async Task <HttpResponseMessage> Get(long fileId) { try { var file = _manager.GetFile(fileId); using (var stream = new FileStream(file.Path, FileMode.Open)) using (var streamContent = new StreamContent(stream)) { var result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(await streamContent.ReadAsByteArrayAsync()) }; result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = file.Name }; result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); return(result); } } catch (Exception ex) { return(new HttpResponseMessage(HttpStatusCode.NotFound)); } }
public static async Task <string> UploadImage(Stream ImageData, IJsonSerializer jsonSerializer, HttpClient httpClient) { StreamContent imageStream = new StreamContent(ImageData); ByteArrayContent imageStreamContent = new ByteArrayContent(await imageStream.ReadAsByteArrayAsync()); MultipartFormDataContent formData = new MultipartFormDataContent(); imageStreamContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); formData.Add(imageStreamContent, "file", "poster.png"); try { HttpResponseMessage res = await httpClient.PostAsync(uploadEndpoint, formData); string responseContent = await res.Content.ReadAsStringAsync(); ImageServiceResponse memesterResponse = jsonSerializer.DeserializeFromString <ImageServiceResponse>(responseContent); if (res.StatusCode == HttpStatusCode.Created) { return(memesterResponse.filePath); } else { throw new Exception($"Status: {res.StatusCode} Server Response: {responseContent}"); } } catch (HttpRequestException e) { throw new Exception(e.Message); } }
public static async Task <int?> Upload(byte[] image) { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("Authorization", "Bearer " + _userToken.access_token); try { using (var content = new MultipartFormDataContent("Upload----")) { var imgStream = new MemoryStream(image); var streamContent = new StreamContent(imgStream); var imageContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result); imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); content.Add(imageContent, "image"); using (var message = await client.PostAsync("http://http://localhost:59646//api/ImageProcessing", content)) { var input = await message.Content.ReadAsStringAsync(); return(JsonConvert.DeserializeObject <int>(input)); } } } catch (Exception e) { string s = e.ToString(); } } return(null); }
public override async Task <InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext context) { var request = context.HttpContext.Request; if (!request.ContentLength.HasValue || request.ContentLength == 0) { return(await InputFormatterResult.FailureAsync()); } var mediaRequest = new ArticleEntryMediaRequest(); using (var streamContent = new StreamContent(request.Body)) { var mediaBytes = await streamContent.ReadAsByteArrayAsync(); var base64Hash = mediaBytes.ComputeMD5HashBase54(); mediaRequest.MediaContent = mediaBytes; mediaRequest.MD5Base64Hash = base64Hash; } mediaRequest.FileName = TryGetFileName(context); mediaRequest.ContentType = TryMediaGetContentType(context); return(await InputFormatterResult.SuccessAsync(mediaRequest)); }
static void Main(string[] args) { if (args.Length < 3) { Environment.Exit(1); } if (!UInt64.TryParse(args[1], out ulong id)) { Console.WriteLine("Arguments not valid."); Environment.Exit(1); } var cookie = args[2]; var url = string.Format("http://data.roblox.com/Data/Upload.ashx?assetid={0}", id); using (var c = new WebClient()) { var h = c.Headers; h.Add("Accept", "*/*"); h.Add("Cookie", ".ROBLOSECURITY=" + cookie); h.Add("Content-Type", "application/xml"); h.Add("User-Agent", "Roblox/WinInet"); using (var str = new StreamContent(new FileStream(args[0], FileMode.Open))) { try { c.UploadData(url, str.ReadAsByteArrayAsync().Result); } catch (WebException) { Console.WriteLine("Upload Failed."); Environment.Exit(2); } } } }
private bool IsStreamContentEqualToFileContent(StreamContent streamContent, string filePath) { byte[] expectedZipByteArr = File.ReadAllBytes(filePath); Task <byte[]> t = streamContent.ReadAsByteArrayAsync(); t.Wait(); return(expectedZipByteArr.SequenceEqual(t.Result)); }
public async Task <IActionResult> Send(Guid id) { StreamContent sc = new StreamContent(HttpContext.Request.Body); var result = await sc.ReadAsByteArrayAsync(); streamQueueManager.AddToQueue(id.ToString(), result); return(Ok()); }
//public static string Authorization(string session_id) //{ // var uri = new Uri("https://api.quatrix.it/api/1.0/session/keepalive"); // WebRequest request = WebRequest.Create(uri); // request.Headers["X-Auth-Token"] = session_id; // WebResponse wr = request.GetResponse(); // Stream receiveStream = wr.GetResponseStream(); // StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8); // string content = reader.ReadToEnd(); // return session_id; //} public static string Upload(string file_name, int id_cat, string session_id) { User user = User_id(session_id); var uri = new Uri("https://serhiy-ivanochko.quatrix.it/api/1.0/upload/link/"); WebRequest request = WebRequest.Create(uri); request.Method = "POST"; request.ContentType = "multipart/form-data"; request.Headers["X-Auth-Token"] = session_id; using (var streamWriter = new StreamWriter(request.GetRequestStream())) { Upload_File u = new Upload_File(); u.name = "37198.bin"; u.parent_id = user.home_id; u.resolve = true; string json = JsonConvert.SerializeObject(u); streamWriter.Write(json); //byte[] bytes = System.IO.File.ReadAllBytes(@"C:\FileGenerator\37198.bin"); //json = JsonConvert.SerializeObject(bytes); //streamWriter.Write(json); } WebResponse wr = request.GetResponse(); Stream receiveStream = wr.GetResponseStream(); StreamReader reader = new StreamReader(receiveStream, Encoding.UTF8); string content = reader.ReadToEnd(); var current_obj = JObject.Parse(content); //return Finalize_upload((string)current_obj["upload_key"], session_id); uri = new Uri("https://serhiy-ivanochko.quatrix.it/api/1.0/upload/chunked/" + (string)current_obj["upload_key"]); HttpClient httpClient = new HttpClient(); MultipartFormDataContent form = new MultipartFormDataContent(); form.Headers.Add("X-Auth-Token", session_id); FileStream fs = File.OpenRead(@"C:\FileGenerator\37198.bin"); var streamContent = new StreamContent(fs); var imageContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result); imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); form.Add(imageContent, "image", Path.GetFileName(@"C:\FileGenerator\37198.bin")); var response = httpClient.PostAsync(uri, form).Result; return(""); }
private static async Task UploadToSharePoint(string path, string siteUrl, string requestUrl, string fieldName, string fieldValue) { using (var handler = new HttpClientHandler { UseDefaultCredentials = true }) { using (var client = new HttpClient(handler)) { client.DefaultRequestHeaders.Add("Accept", "application/json; odata=verbose"); var contextInfo = await client.PostAsync(siteUrl + "_api/contextinfo", null); var contextResponseContent = await contextInfo.Content.ReadAsStringAsync().ConfigureAwait(true); JToken contextObj = JsonConvert.DeserializeObject <dynamic>(contextResponseContent); var digestValue = contextObj["d"]["GetContextWebInformation"]["FormDigestValue"]; client.DefaultRequestHeaders.Add("X-RequestDigest", (string)digestValue); var streamContent = new StreamContent(File.OpenRead(path)); var byteArrayContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result); byteArrayContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); HttpResponseMessage uploadResponse = await client.PostAsync(requestUrl, byteArrayContent).ConfigureAwait(true); var uploadResponseContent = await uploadResponse.Content.ReadAsStringAsync().ConfigureAwait(true); if (uploadResponse.IsSuccessStatusCode) { JToken spFileObj = JsonConvert.DeserializeObject <dynamic>(uploadResponseContent); ClientContext context = new ClientContext(Regex.Replace(requestUrl, "/_api.*", "", RegexOptions.IgnoreCase)); var web = context.Web; var file = web.GetFileByServerRelativeUrl((string)spFileObj.SelectToken("d.ServerRelativeUrl")); var fileItem = file.ListItemAllFields; context.Load(web); context.Load(file); context.Load(fileItem); context.ExecuteQuery(); var wasCheckedOut = file.CheckOutType != CheckOutType.None; if (!wasCheckedOut) { file.CheckOut(); } fileItem.ParseAndSetFieldValue(fieldName, fieldValue); fileItem.Update(); if (!wasCheckedOut) { file.CheckIn(string.Empty, CheckinType.OverwriteCheckIn); } context.ExecuteQuery(); } } } }
public async Task <bool> UploadFileAsync(Stream fs, string fileName, string algorithm, string key) { string fileId = null; using (var form = new MultipartFormDataContent()) using (var streamContent = new StreamContent(fs)) { form.Add(new StringContent(fileName, Encoding.UTF8, "text/plain"), "\"FileName\""); var byteArray = await streamContent.ReadAsByteArrayAsync(); TigerHash tigerHasher = new TigerHash(); byte[] hashed = tigerHasher.Hash(byteArray, byteArray.Length); string hashedBase64String = Convert.ToBase64String(hashed); form.Add(new StringContent(hashedBase64String, Encoding.UTF8, "text/plain"), "\"HashValue\""); Console.WriteLine("Encryption left only"); byte[] encrypted = await EncryptFile(byteArray, algorithm, key); Stream stream = new MemoryStream(encrypted); var encryptedStreamContent = new StreamContent(stream); form.Add(encryptedStreamContent, "\"Content\"", fileName); Console.WriteLine("Form ready to post"); var response = await this.httpClient.PostAsync("api/Files/", form); encryptedStreamContent.Dispose(); if (response.IsSuccessStatusCode) { var responseString = await response.Content.ReadAsStringAsync(); var fileObject = JsonConvert.DeserializeObject <FileResult>(responseString); fileId = fileObject.Id.ToString(); Console.WriteLine("Posted: " + fileId); } } if (String.IsNullOrEmpty(fileId)) { return(false); } // add to localstorage ConfigFileEntry fileEntry = new ConfigFileEntry { Id = fileId, FileName = fileName, Algorithm = algorithm, Key = key }; await AddToLocalStorage(fileEntry); return(true); }
static async System.Threading.Tasks.Task Main(string[] args) { string data = ""; // Get information wiht my token try { WebRequest request = WebRequest.Create("https://api.codenation.dev/v1/challenge/dev-ps/generate-data?token=5fe5322db44b1c301caa43551e71a0d495620f71"); var response = request.GetResponse(); using (Stream dataStream = response.GetResponseStream()) { StreamReader reader = new StreamReader(dataStream); data = reader.ReadToEnd(); } } catch (Exception) { } // Parsing var resultado = JsonConvert.DeserializeObject <Answer>(data); // Decrypt resultado.decifrado = DecryptJulioCesar(1, resultado.cifrado); // SHA1 resultado.resumo_criptografico = HashSha1.Hash(resultado.decifrado); // Show data Console.WriteLine("Cifrado = {0}", resultado.cifrado); Console.WriteLine("Decifrado = {0}", resultado.decifrado); Console.WriteLine("Decifrado = {0}", resultado.resumo_criptografico); // Generate temp file string filePath = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".json"; File.WriteAllText(filePath, JsonConvert.SerializeObject(resultado)); // Post data with multipart/form-data using (var httpClient = new HttpClient()) using (var form = new MultipartFormDataContent()) using (var fs = File.OpenRead(filePath)) using (var streamContent = new StreamContent(fs)) using (var fileContent = new ByteArrayContent(await streamContent.ReadAsByteArrayAsync())) { fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); form.Add(fileContent, "answer", Path.GetFileName(filePath)); HttpResponseMessage response = await httpClient.PostAsync("https://api.codenation.dev/v1/challenge/dev-ps/submit-solution?token=5fe5322db44b1c301caa43551e71a0d495620f71", form); data = await response.Content.ReadAsStringAsync(); } Console.WriteLine("Post Result = {0}", data); Console.ReadKey(); }
public async Task <FileContent> GetFileContentAsync(StreamContent content) { FileContent c = new FileContent(); c.Name = content.Headers.ContentDisposition?.Name; c.FileName = content.Headers.ContentDisposition?.FileName; c.Bytes = await content.ReadAsByteArrayAsync(); return(c); }
public ActionResult UpdateTracks(int dogId, int trainingId, string lostPersonTrackFileName, string dogTrackFileName, Trkseg lostPersonTrackPoints, Trkseg dogTrackPoints) { if (!LoginHelper.IsAuthenticated()) { return(RedirectToAction("Login", "Account")); } else if (!LoginHelper.IsCurrentUserAdmin() && !LoginHelper.IsCurrentUserMember()) { return(RedirectToAction("Error", "Home", new { error = "Nie masz wystarczających uprawnień by zmieniać te dane" })); } var updatedLostPersonTrackStream = new MemoryStream(); var lostPersonFileSerializer = new XmlSerializer(typeof(Trkseg)); lostPersonFileSerializer.Serialize(updatedLostPersonTrackStream, lostPersonTrackPoints); updatedLostPersonTrackStream.Position = 0; var updatedDogTrackStream = new MemoryStream(); var dogFileSerializer = new XmlSerializer(typeof(Trkseg)); dogFileSerializer.Serialize(updatedDogTrackStream, dogTrackPoints); updatedDogTrackStream.Position = 0; MultipartFormDataContent form = new MultipartFormDataContent(); var lostPersonStreamContent = new StreamContent(updatedLostPersonTrackStream); var lostPersonImageContent = new ByteArrayContent(lostPersonStreamContent.ReadAsByteArrayAsync().Result); lostPersonImageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); form.Add(lostPersonImageContent, lostPersonTrackFileName, Path.GetFileName(lostPersonTrackFileName)); var dogStreamContent = new StreamContent(updatedDogTrackStream); var dogImageContent = new ByteArrayContent(dogStreamContent.ReadAsByteArrayAsync().Result); dogImageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); form.Add(dogImageContent, dogTrackFileName, Path.GetFileName(dogTrackFileName)); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", LoginHelper.GetToken()); var responseMessage = client.PostAsync("DogTrainings/Upload", form).Result; if (responseMessage.IsSuccessStatusCode) //200 OK { return(RedirectToAction("Training", new { dogId, trainingId })); //return View("Dog", responseMessage.Content); } else // msg why not ok { ViewBag.Message = "code: " + responseMessage.StatusCode; return(View("Error")); } }
private static MultipartFormDataContent CreateMultiPartForm(Stream blob, string blobName) { string boundry = GenerateRandomBoundry(); MultipartFormDataContent form = new MultipartFormDataContent(boundry); var streamContent = new StreamContent(blob); var blobContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result); blobContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); form.Add(blobContent, "malware", blobName); return(form); }
public static async Task <MultipartFormDataContent> ConvertFormFileToMultipartForm(this IFormFile formFile) { var streamContent = new StreamContent(formFile.OpenReadStream()); var fileContent = new ByteArrayContent(await streamContent.ReadAsByteArrayAsync()); fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); return(new MultipartFormDataContent { { fileContent, "file", formFile.FileName } }); }
public async Task GetAsync_Success_Should_CreateFile_Detail_ExistingFile() { IFileManager fileManager = new LocalFileManager(); await using var file = File.OpenRead(@"Files/TestTextFile.txt"); using var content = new StreamContent(file); var bytes = await content.ReadAsByteArrayAsync(); var readedBytes = await fileManager.GetAsync("Files/TestTextFile.txt"); readedBytes.SequenceEqual(bytes).Should().BeTrue(); }
private static async Task <byte[]> GetUploadedPicture(IFormFile file) { byte[] imageByteArray = null; using (var client = new HttpClient()) { HttpContent content = new StreamContent(file.OpenReadStream()); imageByteArray = await content.ReadAsByteArrayAsync(); // serialize the http content to a byte array } return(imageByteArray); }
public static async Task <string> Upload(string module, string path) { var userInfo = Option.GetUserInfo(); string url = userInfo.Server + module; string username = userInfo.UserName; string password = userInfo.Password; try { System.Net.ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true; using (var client = new HttpClient()) { client.Timeout = new TimeSpan(1, 0, 0); // 1 hour var authValue = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes($"{username}:{password}"))); client.DefaultRequestHeaders.Authorization = authValue; MultipartFormDataContent form = new MultipartFormDataContent(); using (FileStream fs = File.OpenRead(path)) { var streamContent = new StreamContent(fs); var imageContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result); imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); form.Add(imageContent, "filedata", Path.GetFileName(path)); } var response = await client.PostAsync(url, form); StatusCode = (int)response.StatusCode; IsSuccessStatus = response.IsSuccessStatusCode; var responseContent = response.Content; string responseString = await responseContent.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { } else { LogClass.WriteWbLog("", "", "", "Upload", module, string.Format("Response Exception with status code : {0}" + "Output :" + responseString, response.StatusCode), url); } return(responseString); } } catch (Exception ex) { LogClass.WriteWbLog("", "", "", "Upload Exception", module, ex.Message, url); } return(""); }