WPF (C #), how to use a mail request to transfer a file?

I have an image represented as an array of bytes. I need to save it to a file and send a mail request. Tell us how to do it better.

That's what I'm doing

private Stream file; public void Fun1() { using (file = IsolatedStorageHelper.OpenFile(Picture, FileMode.Create)) { file.Write(bt, 0, bt.Length); _cookies = DataHolder.Instance.Cookies; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(String.Concat("http:// Mysite.com/image.php?image=FILE",file)); request.Method = "POST"; request.ContentType = "multipart/form-data"; request.CookieContainer = _cookies; request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackPlayersfun1), request); } } private void GetRequestStreamCallbackPlayersfun1(IAsyncResult asynchronousResult) { HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; Stream postStream = request.EndGetRequestStream(asynchronousResult); using (file = IsolatedStorageHelper.OpenFile(Picture, FileMode.Open)) { BinaryReader br = new BinaryReader(file, Encoding.UTF8); byte[] buffer = br.ReadBytes(2048); while (buffer.Length > 0) { postStream.Write(buffer, 0, buffer.Length); buffer = br.ReadBytes(2048); } } postStream.Close(); request.BeginGetResponse(new AsyncCallback(ReadCallbackSavePlayersfun1), request); } private void ReadCallbackSavePlayersfun1(IAsyncResult asynchronousResult) { lock (__SYNC) { HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult); } } 

As a result, the server did not come, tell me what I'm doing wrong


thanks for your reply.

But I have a different problem. My photo is encoded in a line, a line that I write to the stream, and try to send to the server. In response, everything is fine, but the request type is "Get" (responsibility variable, ReadCallbackSavePlayersfun1 method). Please tell me what is wrong.

 public void Fun1() { string str = "iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAA"; using (file = IsolatedStorageHelper.OpenFile(Picture, FileMode.Create)) { StreamWriter w = new StreamWriter(file,Encoding.UTF8); w.WriteLine(str); _cookies = DataHolder.Instance.Cookies; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(String.Concat("http://Mysite.com/image.php")); string boundary = "----------" + DateTime.UtcNow.Ticks.ToString("x", CultureInfo.InvariantCulture); request.Method = "POST"; request.ContentType = "multipart/form-data; boundary=" + boundary; request.CookieContainer = _cookies; request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallbackPlayersfun1), request); w.Close(); } } private void GetRequestStreamCallbackPlayersfun1(IAsyncResult asynchronousResult) { HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; Stream postStream = request.EndGetRequestStream(asynchronousResult); string boundary = "----------" + DateTime.UtcNow.Ticks.ToString("x", CultureInfo.InvariantCulture); var sbHeader = new StringBuilder(); if (file != null) { sbHeader.AppendFormat("--{0}\r\n", boundary); sbHeader.AppendFormat("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n", "picture", file); sbHeader.AppendFormat("Content-Type: {0}\r\n\r\n", request.ContentType); } using (file = IsolatedStorageHelper.OpenFile(Picture, FileMode.Open)) { byte[] header = Encoding.UTF8.GetBytes(sbHeader.ToString()); byte[] footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); long contentLength = header.Length + (file != null ? file.Length : 0) + footer.Length; postStream.Write(header, 0, header.Length); if (file != null) { BinaryReader br = new BinaryReader(file, Encoding.UTF8); byte[] buffer = br.ReadBytes(2048); while (buffer.Length > 0) { postStream.Write(buffer, 0, buffer.Length); buffer = br.ReadBytes(2048); } br.Close(); } postStream.Write(footer, 0, footer.Length); postStream.Flush(); postStream.Close(); } request.BeginGetResponse(new AsyncCallback(ReadCallbackSavePlayersfun1), request); } private void ReadCallbackSavePlayersfun1(IAsyncResult asynchronousResult) { lock (__SYNC) { HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState; HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult); try { String doc = ""; using (Stream streamResponse = response.GetResponseStream()) { Encoding encode = System.Text.Encoding.GetEncoding("utf-8"); StreamReader readStream = new StreamReader(streamResponse, encode); Char[] read = new Char[256]; int count = readStream.Read(read, 0, 256); while (count > 0) { String str = new String(read, 0, count); doc += str; count = readStream.Read(read, 0, 256); } } } catch { } } } 
+4
source share
1 answer

Posting web bytes [] of data in .Net is not so simple. Saving byte[] to the repository is very simple, so I will not have code for this, but here is the method I use to send binary data.

This is from http://skysanders.net/subtext/archive/2010/04/12/c-file-upload-with-form-fields-cookies-and-headers.aspx with my changes as per

And to get FileInfo just go to

 new FileInfo(fullPath) 

Good luck :)

  /// <summary> /// Create a new HttpWebRequest with the default properties for HTTP POSTS /// </summary> /// <param name="url">The URL to be posted to</param> /// <param name="referer">The refer</param> /// <param name="cookies">CookieContainer that should be used in this request</param> /// <param name="postData">The post data</param> private string CreateHttpWebUploadRequest(string url, string referer, CookieContainer cookies, NameValueCollection postData, FileInfo fileData, string fileContentType) { var request = (HttpWebRequest)HttpWebRequest.Create(url); string boundary = "----------" + DateTime.UtcNow.Ticks.ToString("x", CultureInfo.InvariantCulture); // set the request variables request.Method = WebRequestMethods.Http.Post; request.ContentType = "multipart/form-data; boundary=" + boundary; request.CookieContainer = cookies; request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.4 (KHTML, like Gecko) Chrome/5.0.375.55 Safari/533.4"; request.Accept = "image/gif, image/jpeg, image/pjpeg, image/pjpeg, */*"; request.Headers.Add("Accept-Encoding: gzip,deflate"); request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip; request.Headers.Add("Accept-Language: en-us"); request.Referer = referer; request.KeepAlive = true; request.AllowAutoRedirect = false; // process through the fields var sbHeader = new StringBuilder(); // add form fields, if any if (postData != null) { foreach (string key in postData.AllKeys) { string[] values = postData.GetValues(key); if (values != null) { foreach (string value in values) { if (!string.IsNullOrEmpty(value)) sbHeader.AppendFormat("--{0}\r\n", boundary); sbHeader.AppendFormat("Content-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}\r\n", key, value); } } } } if (fileData != null) { sbHeader.AppendFormat("--{0}\r\n", boundary); sbHeader.AppendFormat("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n", "media", fileData.Name); sbHeader.AppendFormat("Content-Type: {0}\r\n\r\n", fileContentType); } byte[] header = Encoding.UTF8.GetBytes(sbHeader.ToString()); byte[] footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); long contentLength = header.Length + (fileData != null ? fileData.Length : 0) + footer.Length; // set content length request.ContentLength = contentLength; // ref http://stackoverflow.com/questions/2859790/the-request-was-aborted-could-not-create-ssl-tls-secure-channel // avoid The request was aborted: Could not create SSL/TLS secure channel exception ServicePointManager.Expect100Continue = false; ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; using (var requestStream = request.GetRequestStream()) { requestStream.Write(header, 0, header.Length); // write the uploaded file if (fileData != null) { // write the file data, if any byte[] buffer = new Byte[fileData.Length]; var bytesRead = fileData.OpenRead().Read(buffer, 0, (int)(fileData.Length)); requestStream.Write(buffer, 0, bytesRead); } // write footer requestStream.Write(footer, 0, footer.Length); requestStream.Flush(); requestStream.Close(); using (var response = request.GetResponse() as HttpWebResponse) using (var stIn = new System.IO.StreamReader(response.GetResponseStream())) { return stIn.ReadToEnd(); } } } 
+1
source

Source: https://habr.com/ru/post/1444283/


All Articles