当前位置:编程学习 > C#/ASP.NET >>

HttpWebRequest上传图片问题。


        public void getUp()
        {
            String fileToUpload = "c:\\1.jpg";
            String uploadUrl = "https://www.ganji.com/swftool/uploader2/includes/upload.php";
            String fileFormName = "file";
            String contenttype = "gif,jpg,jpeg,png,bmp";
            string boundary = "----------" + DateTime.Now.Ticks.ToString("x");

            HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uploadUrl);
            webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
            webrequest.Method = "POST";
            webrequest.CookieContainer = myCookieContainer;
            StringBuilder sb = new StringBuilder();
            sb.Append("--");
            sb.Append(boundary);
            sb.Append("\r\n");
            sb.Append("Content-Disposition: form-data; name=\"");
            sb.Append(fileFormName);
            sb.Append("\"; filename=\"");
            sb.Append(Path.GetFileName(fileToUpload));
            sb.Append("\"");
            sb.Append("\r\n");
            sb.Append("Content-Type: ");
            sb.Append(contenttype);
            sb.Append("\r\n");
            sb.Append("\r\n");

            string postHeader = sb.ToString();
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);
            byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
            FileStream fileStream = new FileStream(fileToUpload, FileMode.Open, FileAccess.Read);
            long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;
            webrequest.ContentLength = length;
            Stream requestStream = webrequest.GetRequestStream();
            requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

            byte[] buffer = new Byte[(int)fileStream.Length];
            int bytesRead = 0;
            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                requestStream.Write(buffer, 0, bytesRead);
            requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
            requestStream.Close();
        }
--------------------编程问答--------------------

你的问题呢? --------------------编程问答--------------------

还有 你把你的拼接字符串传到哪里去了呢? --------------------编程问答-------------------- QQ504402105 麻烦加我!!!  我告诉你!!
补充:.NET技术 ,  C#
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,