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

            }
        }

その結果、サーバーが来ませんでした。何が間違っているのか教えてください


お返事をありがとうございます。

しかし、私には別の問題があります。私の写真は文字列にエンコードされています。この文字列はストリームに書き込んでサーバーに送信しようとしています。応答では、すべて OK が返されますが、要求のタイプは "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[]は簡単なので、そのためのコードはありませんが、バイナリ データを投稿するために使用する方法を次に示します。

これはもともと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 に答える