4

我有一张以字节数组形式呈现的图片。我需要将其保存到文件并发送发布请求。告诉我如何做得更好

这是我所做的

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);

            }
        }

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


感谢您的回复。

但我还有另一个问题。我的图片被编码在一个字符串中,我将字符串写入流并尝试发送到服务器。作为响应,一切正常,但请求的类型是“Get”(可变响应,方法 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, 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

1 回答 1

1

在 .Net 中发布 web byte[] 数据并不是那么简单。将 a 保存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, 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();
            }
        }
    }
于 2012-11-06T12:30:44.330 回答