WPF(C#)如何使用post请求传输文件?

WPF(C#)如何使用post请求传输文件?,第1张

概述我有一个以字节数组的形式呈现的图片.我需要将其保存到文件并发送帖子请求.告诉我如何做得更好 这就是我的工作 private Stream file; public void Fun1() { using (file = IsolatedStorageHelper.OpenFile(Picture, FileMode.Create)) { file. 我有一个以字节数组的形式呈现的图片.我需要将其保存到文件并发送帖子请求.告诉我如何做得更好

这就是我的工作

private Stream file; public voID Fun1()  {   using (file = IsolatedStorageHelper.Openfile(Picture,fileMode.Create))      {       file.Write(bt,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,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);            }        }

结果,服务器没有来,告诉我我做错了什么

感谢您的回复.

但我有另一个问题.我的图片以字符串编码,我写入流中的字符串并尝试发送到服务器.作为回应,一切都很好,但请求的类型是“获取”(变量响应,方法ReadCallbackSavePlayersfun1).请告诉我出了什么问题

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,header.Length); if (file != null){                BinaryReader br = new BinaryReader(file,EnCoding.UTF8);                byte[] buffer = br.ReadBytes(2048);                while (buffer.Length > 0){                    poststream.Write(buffer,buffer.Length);                    buffer = br.ReadBytes(2048); }                br.Close();}            poststream.Write(footer,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,256);                        while (count > 0){                            String str = new String(read,count);                            doc += str;                            count = readStream.Read(read,256);}}}                catch { }}}
解决方法 在.Net中发布web byte []数据并不那么简单.将byte []保存到存储很容易,因此我没有代码,但这是我用来发布二进制数据的方法.

这最初来自http://skysanders.net/subtext/archive/2010/04/12/c-file-upload-with-form-fields-cookies-and-headers.aspx,我的修改适合

要获取fileInfo,只需传入即可

new fileInfo(fullPath)

祝好运 : )

/// <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,*/*";        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","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 https://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,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,(int)(fileData.Length));                requestStream.Write(buffer,bytesRead);            }            // write footer            requestStream.Write(footer,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();            }        }    }
总结

以上是内存溢出为你收集整理的WPF(C#)如何使用post请求传输文件?全部内容,希望文章能够帮你解决WPF(C#)如何使用post请求传输文件?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1229359.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存