Skip to content

Instantly share code, notes, and snippets.

@figloalds
Created December 28, 2017 19:23
Show Gist options
  • Save figloalds/6b2f781a4f17a4e7d052c2af5b007bc1 to your computer and use it in GitHub Desktop.
Save figloalds/6b2f781a4f17a4e7d052c2af5b007bc1 to your computer and use it in GitHub Desktop.
public static void EnviarArquivo(string url, string arquivo, string param, string contentType, NameValueCollection dadosFormulario) {
string b = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] bBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + b + "\r\n");
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.ContentType = "multipart/form-data; boundary=" + b;
req.Method = "POST";
req.KeepAlive = true;
Stream reqStream = req.GetRequestStream();
string template = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
foreach (string key in dadosFormulario.Keys) {
reqStream.Write(bBytes, 0, bBytes.Length);
string itemForm = string.Format(template, key, dadosFormulario[key]);
byte[] bytesItem = System.Text.Encoding.UTF8.GetBytes(itemForm);
reqStream.Write(bytesItem, 0, bytesItem.Length);
}
reqStream.Write(bBytes, 0, bBytes.Length);
string templateHeader = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(templateHeader, param, arquivo, contentType);
byte[] bytesHeader = System.Text.Encoding.UTF8.GetBytes(header);
reqStream.Write(bytesHeader, 0, bytesHeader.Length);
FileStream fs = new FileStream(arquivo, FileMode.Open, FileAccess.Read);
fs.CopyTo(reqStream);
byte[] trail = System.Text.Encoding.ASCII.GetBytes("\r\n--" + b + "--\r\n");
reqStream.Write(trail, 0, trail.Length);
reqStream.Close();
WebResponse resp = null;
try {
using (resp = req.GetResponse()) {
using (Stream respStream = resp.GetResponseStream()) {
StreamReader respReader = new StreamReader(respStream);
Console.WriteLine($"Resposta do Servidor: {respReader.ReadToEnd()}");
}
}
} catch (Exception ex) {
Console.WriteLine($"Erro ao subir o arquivo {ex.Message} {ex.StackTrace}");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment