Ejemplo n.º 1
0
        public static UploadFileResponse HttpWebRequestUploadFile(OneSkyService service, string url, string file, string paramName, Stream fileStream, string contentType)
        {
            string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");

            byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

            req.ContentType = "multipart/form-data; boundary=" + boundary;
            req.Method      = "POST";
            req.KeepAlive   = true;

            using (var DataStream = new BinaryWriter(req.GetRequestStream(), System.Text.Encoding.UTF8))
            {
                DataStream.Write(boundarybytes, 0, boundarybytes.Length);

                string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
                string header         = string.Format(headerTemplate, paramName, file, contentType);
                byte[] headerbytes    = System.Text.Encoding.UTF8.GetBytes(header);
                DataStream.Write(headerbytes, 0, headerbytes.Length);


                byte[] buffer    = new byte[4096];
                int    bytesRead = 0;
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    DataStream.Write(buffer, 0, bytesRead);
                }

                byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                DataStream.Write(trailer, 0, trailer.Length);
                DataStream.Flush();
                DataStream.Close();
            }

            try
            {
                using (HttpWebResponse Response = (HttpWebResponse)req.GetResponse())
                {
                    using (Stream rawResponseStream = Response.GetResponseStream())
                    {
                        var responseText = service.StreamToString(rawResponseStream);
                        if (!string.IsNullOrWhiteSpace(responseText))
                        {
                            using (var responseStream = service.StringToStream(responseText))
                            {
                                var jsonSerializer = new DataContractJsonSerializer(typeof(UploadFileResponse));
                                return((UploadFileResponse)jsonSerializer.ReadObject(responseStream));
                            }
                        }
                    }
                }
            }
            catch (WebException)
            {
            }
            return(null);
        }