HttpWebRequest 上传文件和参数带进度条

ContractedBlock.gif ExpandedBlockStart.gif Code
  1public int StartUpload()
  2ExpandedBlockStart.gifContractedBlock.gif        {
  3            int returnValue = 0;
  4            if (string.IsNullOrEmpty(this.URL) || string.IsNullOrEmpty(this.FileNamePath) || string.IsNullOrEmpty(this.SaveFileName) || this.ProgressBar == null)
  5                return returnValue;
  6
  7            using (FileStream fs = new FileStream(this.FileNamePath, FileMode.Open, FileAccess.Read))
  8ExpandedSubBlockStart.gifContractedSubBlock.gif            {
  9                using (BinaryReader r = new BinaryReader(fs))
 10ExpandedSubBlockStart.gifContractedSubBlock.gif                {
 11                    //时间戳
 12                    string strBoundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
 13
 14                    //请求文件信息
 15                    StringBuilder sbFile = new StringBuilder();
 16                    sbFile.Append("--");
 17                    sbFile.Append(strBoundary);
 18                    sbFile.Append("\r\n");
 19                    sbFile.Append("Content-Disposition: form-data; name=\"");
 20                    sbFile.Append("file");
 21                    sbFile.Append("\"; filename=\"");
 22                    sbFile.Append(this.SaveFileName);
 23                    sbFile.Append("\"");
 24                    sbFile.Append("\r\n");
 25                    sbFile.Append("Content-Type: ");
 26                    sbFile.Append("application/octet-stream");
 27                    sbFile.Append("\r\n");
 28                    sbFile.Append("\r\n");
 29                    byte[] postFileBytes = Encoding.UTF8.GetBytes(sbFile.ToString());
 30
 31                    //请求参数信息
 32                    StringBuilder sbData = new StringBuilder();
 33                    sbData.Append("\r\n--");
 34                    sbData.Append(strBoundary);
 35                    sbData.Append("\r\n");
 36                    sbData.Append("Content-Disposition: form-data; name=\"pId1\"");
 37                    sbData.Append("\r\n");
 38                    sbData.Append("\r\n");
 39                    sbData.Append(this.PID1);
 40                    sbData.Append("\r\n--");
 41                    sbData.Append(strBoundary);
 42                    sbData.Append("\r\n");
 43                    sbData.Append("Content-Disposition: form-data; name=\"pId2\"");
 44                    sbData.Append("\r\n");
 45                    sbData.Append("\r\n");
 46                    sbData.Append(this.PID2);
 47                    sbData.Append("\r\n--");
 48                    sbData.Append(strBoundary);
 49                    sbData.Append("\r\n");
 50                    sbData.Append("Content-Disposition: form-data; name=\"pId3\"");
 51                    sbData.Append("\r\n");
 52                    sbData.Append("\r\n");
 53                    sbData.Append(this.PID3);
 54                    sbData.Append("\r\n--");
 55                    sbData.Append(strBoundary);
 56                    sbData.Append("--");
 57                    byte[] postDataBytes = Encoding.UTF8.GetBytes(sbData.ToString());
 58
 59                    // 根据uri创建HttpWebRequest对象
 60                    HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(this.URL));
 61                    httpReq.Method = "POST";
 62
 63                    //对发送的数据不使用缓存
 64                    httpReq.AllowWriteStreamBuffering = false;
 65
 66                    //设置获得响应的超时时间(300秒)
 67                    httpReq.Timeout = 300000;
 68                    httpReq.ContentType = "multipart/form-data; boundary=" + strBoundary;
 69
 70                    long length = fs.Length + postFileBytes.Length + postDataBytes.Length;
 71
 72                    long fileLength = fs.Length;
 73                    httpReq.ContentLength = length;
 74
 75                    this.ProgressBar.Maximum = int.MaxValue;
 76                    this.ProgressBar.Minimum = 0;
 77                    this.ProgressBar.Value = 0;
 78
 79                    //每次上传4k
 80                    int bufferLength = 4096;
 81                    byte[] buffer = new byte[bufferLength];
 82
 83                    //已上传的字节数
 84                    long offset = 0;
 85
 86                    //开始上传时间
 87                    DateTime startTime = DateTime.Now;
 88                    this.IsUploading = true;
 89                    int size = r.Read(buffer, 0, bufferLength);
 90                    using (Stream postStream = httpReq.GetRequestStream())
 91ExpandedSubBlockStart.gifContractedSubBlock.gif                    {
 92                        //发送请求头部消息
 93                        postStream.Write(postFileBytes, 0, postFileBytes.Length);
 94                        while (size > 0)
 95ExpandedSubBlockStart.gifContractedSubBlock.gif                        {
 96                            if (!this.IsUploading)
 97ExpandedSubBlockStart.gifContractedSubBlock.gif                            {
 98                                return 0;
 99                            }

100                            postStream.Write(buffer, 0, size);
101                            offset += size;
102                            this.ProgressBar.Value = (int)(offset * (int.MaxValue / length));
103                            TimeSpan span = DateTime.Now - startTime;
104                            double second = span.TotalSeconds;
105                            App.DoEvents();
106                            size = r.Read(buffer, 0, bufferLength);
107                        }

108                        this.ProgressBar.Value = this.ProgressBar.Maximum;
109                        //添加请求尾部信息
110                        postStream.Write(postDataBytes, 0, postDataBytes.Length);
111                    }

112
113                    //获取服务器端的响应
114                    WebResponse webRespon = httpReq.GetResponse();
115                    using (Stream s = webRespon.GetResponseStream())
116ExpandedSubBlockStart.gifContractedSubBlock.gif                    {
117                        using (StreamReader sr = new StreamReader(s))
118ExpandedSubBlockStart.gifContractedSubBlock.gif                        {
119                            //读取服务器端返回的消息
120                            String sReturnString = sr.ReadLine();
121                            if (sReturnString == "Success")
122ExpandedSubBlockStart.gifContractedSubBlock.gif                            {
123                                returnValue = 1;
124                            }

125                            else if (sReturnString == "Error")
126ExpandedSubBlockStart.gifContractedSubBlock.gif                            {
127                                returnValue = 0;
128                            }

129                        }

130                    }

131                }

132            }

133            this.IsUploading = false;
134            if (returnValue == 1)
135                this.OnUploadFileSuccessed(this);
136            else
137                this.OnUploadFileErrored(this);
138            return returnValue;
139        }

转载于:https://www.cnblogs.com/xsi640/articles/1593230.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值