发送文件

string PostData(HttpPostedFile postedFile, string url)
        {
            try
            {
                WebRequest req = WebRequest.Create(url);
                req.Method = "POST";

                String boundary = "---------------------------7d4a6d158c9"; // 分隔符 
                StringBuilder sb = new StringBuilder();
                // 发送每个字段: 
                //sb = sb.Append("--");
                //sb = sb.Append(boundary);
                //sb = sb.Append("\r\n");
                //sb = sb.Append("Content-Disposition: form-data; name=\"MailIDs\"\r\n\r\n");
                //sb = sb.Append(Server.UrlEncode("1111111111"));
                //sb = sb.Append("\r\n");
                // 发送文件: 
                sb = sb.Append("--");
                sb = sb.Append(boundary);
                sb = sb.Append("\r\n");
                sb = sb.Append("Content-Disposition: form-data; name=\"" + Server.UrlEncode(Path.GetFileNameWithoutExtension(postedFile.FileName)) 
                    + "\"; filename=\"" + Server.UrlEncode(postedFile.FileName) + "\"\r\n");
                sb = sb.Append("Content-Type: application/octet-stream\r\n\r\n");
                byte[] data = Encoding.UTF8.GetBytes(sb.ToString());

                byte[] end_data = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); 


                req.ContentType = "multipart/form-data; boundary=" + boundary;

                // Encode the data
                byte[] encodedBytes = new byte[postedFile.InputStream.Length];

                req.ContentLength = data.Length + encodedBytes.Length + end_data.Length;

                postedFile.InputStream.Read(encodedBytes, 0, encodedBytes.Length);

                // Write encoded data into request stream
                using (Stream requestStream = req.GetRequestStream())
                {
                    requestStream.Write(data, 0, data.Length);
                    requestStream.Write(encodedBytes, 0, encodedBytes.Length);
                    requestStream.Write(end_data, 0, end_data.Length);
                    requestStream.Close();

                    using (WebResponse res = req.GetResponse())
                    {
                        using (Stream receiveStream = res.GetResponseStream())
                        {
                            StreamReader sr = new StreamReader(receiveStream);
                            return sr.ReadToEnd();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorLog.WriteErrorLog("URL:" + url + ex.ToString());
                return "";
            }
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值