通过C#使用HTTP POST上传图片文件时出现文件格式问题

时间:2012-08-07 16:02:52

标签: c# api httpwebrequest

SDO REST API - 问题是,当我上传文件时,它没有格式,它看起来像这样:98A9799C-CFB1-423B-A4AD-40609282F861(2.7 MB)DELETE< ---此文件需要是picture.jpg

该文件只是picture.jpg

public string POST(string URI, string file)
        {
            NetworkCredential credentials = new NetworkCredential();
            credentials.UserName = AppVars.Username;
            credentials.Password = AppVars.Password;

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URI);
            request.Credentials = credentials;
            request.Method = WebRequestMethods.Http.Post;
            request.ContentType = "application/x-www-form-urlencoded";
            //I have also tried request.ContentType = "image/jpeg"; and ran into the same issue.

            byte[] bytes = File.ReadAllBytes(file);
            Stream os = null;
            try
            { 
                request.ContentLength = bytes.Length;   
                os = request.GetRequestStream();
                os.Write(bytes, 0, bytes.Length);         
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (os != null)
                {
                    os.Close();
                }
            }
            try
            { 
                WebResponse requestResponse = request.GetResponse();
                if (requestResponse == null)
                { return null; }
                StreamReader sr = new StreamReader(requestResponse.GetResponseStream());
                return sr.ReadToEnd().Trim();
            }
            catch (WebException ex)
            {
                MessageBox.Show(ex.Message);
            }
            return null;
        }

1 个答案:

答案 0 :(得分:0)

问题解决了。这是一个缓存问题。我清除了浏览器缓存,并且能够在线查看图像。