Skip to content

Instantly share code, notes, and snippets.

@oliveira-michel
Created March 18, 2020 21:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oliveira-michel/c2833f330c0cf51eabb7ca7c698646cf to your computer and use it in GitHub Desktop.
Save oliveira-michel/c2833f330c0cf51eabb7ca7c698646cf to your computer and use it in GitHub Desktop.
Exemplo de cliente enviando um arquivo via HTTP via multipart e recebendo outro de volta
public void Teste()
{
var retorno = PostAndGetArquivo();
byte[] bytesImagem;
using (MemoryStream ms = new MemoryStream())
{
retorno.CopyTo(ms);
bytesImagem = ms.ToArray();
}
File.WriteAllBytes($"c:\\teste.pdf", bytesImagem);
}
public Stream PostAndGetArquivo()
{
var http = (HttpWebRequest) WebRequest.Create("http://xxx/yyy");
http.Method = "POST";
var sendFile = File.ReadAllBytes("c:\\exemplo.rtf");
var byteArrayContent = new ByteArrayContent(sendFile);
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(byteArrayContent, "file", "exemplo.rtf");
foreach (KeyValuePair<string, IEnumerable<string>> multipartContentHeader in multipartContent.Headers)
{
http.Headers.Add(multipartContentHeader.Key,
multipartContentHeader.Value.Aggregate((current, next) => $"{current},{next}"));
}
var stringToSend = new StreamReader(multipartContent.ReadAsStreamAsync().Result).ReadToEnd();
using (var streamWriter = new StreamWriter(http.GetRequestStream()))
{
streamWriter.Write(stringToSend);
}
var response = http.GetResponse();
return response.GetResponseStream();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment