コード例 #1
0
        private async Task <bool> UploadFile(TaskItem <bool> aTaskItem, CancellationToken cancellationToken, dynamic info)
        {
            float percentComplete = 0;

            aTaskItem.Progress?.Report(percentComplete);
            aTaskItem.TaskStatus = TaskStatusEnum.InProgress;
            // 时间戳,用做boundary
            string timeStamp = DateTime.Now.Ticks.ToString("x");

            string         token   = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MDAxMTI3NjgsInVzZXJfbmFtZSI6IldDc0FSRzIzSm0gMU9FaDhQTG9haHc9PSIsImp0aSI6IjhjYWUzNTQzLWIwZTAtNDlkOS1iMTQ4LTRkYWJmYjgzNmMxYyIsImNsaWVudF9pZCI6InByaXZhdGVfY2xpZW50X3dpbmRvd3MiLCJzY29wZSI6WyJzY29wZV9jb3JlIl19.LhLLc9kMsK2B5oUx5RMpO1tLND0xS-7lt2C3kQ3mVgk";
            HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(@"http://172.18.19.101:8888/testimony/api/v1/files"));

            httpReq.Method = "POST";
            httpReq.Headers.Add("Authorization", $"Bearer {token}");
            httpReq.AllowWriteStreamBuffering = false;
            httpReq.Timeout = 1800000;

            httpReq.ContentType = "multipart/form-data; boundary=" + timeStamp;
            httpReq.KeepAlive   = false;
            httpReq.ServicePoint.Expect100Continue = false;
            try
            {
                using (FileStream fileStream = new FileStream(aTaskItem.FilePath, FileMode.Open, FileAccess.Read))
                {
                    using (BinaryReader binaryReader = new BinaryReader(fileStream))
                    {
                        //头信息
                        string boundary      = timeStamp;
                        string startBoundary = "--" + timeStamp;
                        string dataFormat    = "\r\n" + startBoundary +
                                               "\r\nContent-Disposition: form-data; name=\"{0}\";filename=\"{1}\" \r\nContent-Type:application/octet-stream\r\n\r\n";

                        string header = string.Format(dataFormat, "fileName", aTaskItem.TaskName);

                        byte[] postHeaderBytes = Encoding.UTF8.GetBytes(header);

                        //------------------------------[form-data Start]----------------------------
                        string reqFormat = startBoundary + "\r\nContent-Type:text/plain;charset=UTF-8" +
                                           "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
                        string req      = string.Format(reqFormat, "name", aTaskItem.TaskName);
                        byte[] reqBytes = Encoding.UTF8.GetBytes(req);

                        //结束边界
                        byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + timeStamp + "--\r\n");
                        //------------------------------[form-data End]----------------------------

                        byte[] reqBytes1;
                        //------------------------------[form-data Start]----------------------------
                        reqFormat = startBoundary + "\r\nContent-Type:text/plain;charset=UTF-8" +
                                    "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
                        req       = string.Format(reqFormat, "reserveId", "33ab029654234c2994a67d748c670953");
                        reqBytes1 = Encoding.UTF8.GetBytes(req);
                        //------------------------------[form-data End]----------------------------

                        //------------------------------[form-data Start]----------------------------
                        reqFormat = startBoundary + "\r\nContent-Type:text/plain;charset=UTF-8" +
                                    "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
                        req = string.Format(reqFormat, "participantId", "3c45facd57bb471b868c79888f772794");
                        byte[] reqBytes2 = Encoding.UTF8.GetBytes(req);
                        //------------------------------[form-data End]----------------------------

                        //------------------------------[form-data Start]----------------------------
                        reqFormat = startBoundary + "\r\nContent-Type:text/plain;charset=UTF-8" +
                                    "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
                        req = string.Format(reqFormat, "suffix", System.IO.Path.GetExtension(aTaskItem.FilePath).TrimStart('.'));
                        byte[] reqBytes3 = Encoding.UTF8.GetBytes(req);
                        //------------------------------[form-data End]----------------------------

                        //------------------------------[form-data Start]----------------------------
                        reqFormat = startBoundary + "\r\nContent-Type:text/plain;charset=UTF-8" +
                                    "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
                        req = string.Format(reqFormat, "ascription", 2);
                        byte[] reqBytes4 = Encoding.UTF8.GetBytes(req);
                        //------------------------------[form-data End]----------------------------

                        //------------------------------[form-data Start]----------------------------
                        reqFormat = startBoundary + "\r\nContent-Type:text/plain;charset=UTF-8" +
                                    "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
                        req = string.Format(reqFormat, "uploadFileId", aTaskItem.TaskId);
                        byte[] reqBytes5 = Encoding.UTF8.GetBytes(req);
                        //------------------------------[form-data End]----------------------------

                        //------------------------------[form-data Start]----------------------------
                        reqFormat = startBoundary + "\r\nContent-Type:text/plain;charset=UTF-8" +
                                    "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
                        req = string.Format(reqFormat, "source", 1);
                        byte[] reqBytes6 = Encoding.UTF8.GetBytes(req);
                        //------------------------------[form-data End]----------------------------
                        //------------------------------[form-data Start]----------------------------
                        reqFormat = startBoundary + "\r\nContent-Type:text/plain;charset=UTF-8" +
                                    "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
                        req = string.Format(reqFormat, "ajbh", "3f2f2a593bfe4203a3bcb91d28bbac4e");
                        byte[] reqBytes7 = Encoding.UTF8.GetBytes(req);
                        //------------------------------[form-data End]----------------------------
                        //------------------------------[form-data Start]----------------------------
                        reqFormat = startBoundary + "\r\nContent-Type:text/plain;charset=UTF-8" +
                                    "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
                        req = string.Format(reqFormat, "uploader", "孙建远");
                        byte[] reqBytes8 = Encoding.UTF8.GetBytes(req);
                        //------------------------------[form-data End]----------------------------
                        //------------------------------[form-data Start]----------------------------
                        reqFormat = startBoundary + "\r\nContent-Type:text/plain;charset=UTF-8" +
                                    "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";
                        req = string.Format(reqFormat, "jbfy", "2401");
                        byte[] reqBytes9 = Encoding.UTF8.GetBytes(req);
                        //------------------------------[form-data End]----------------------------
                        //------------------------------[form-data Start]----------------------------
                        reqFormat = startBoundary + "\r\nContent-Type:text/plain;charset=UTF-8" +
                                    "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
                        req = string.Format(reqFormat, "reservepattern", 2);
                        byte[] reqBytes10 = Encoding.UTF8.GetBytes(req);
                        //------------------------------[form-data End]----------------------------

                        long length = fileStream.Length + postHeaderBytes.Length + boundaryBytes.Length + reqBytes.Length
                                      + reqBytes1.Length + reqBytes2.Length + reqBytes3.Length + reqBytes4.Length +
                                      reqBytes5.Length + reqBytes6.Length + reqBytes7.Length + reqBytes8.Length
                                      + reqBytes9.Length + reqBytes10.Length;


                        httpReq.ContentLength = length; //请求内容长度

                        //每次上传8k
                        int    bufferLength = 8192;
                        byte[] buffer       = new byte[bufferLength];

                        int    size       = binaryReader.Read(buffer, 0, bufferLength);
                        Stream postStream = httpReq.GetRequestStream();

                        //发送请求头部消息
                        postStream.Write(reqBytes, 0, reqBytes.Length);
                        postStream.Write(reqBytes1, 0, reqBytes1.Length);
                        postStream.Write(reqBytes2, 0, reqBytes2.Length);
                        postStream.Write(reqBytes3, 0, reqBytes3.Length);
                        postStream.Write(reqBytes4, 0, reqBytes4.Length);
                        postStream.Write(reqBytes5, 0, reqBytes5.Length);
                        postStream.Write(reqBytes6, 0, reqBytes6.Length);
                        postStream.Write(reqBytes7, 0, reqBytes7.Length);
                        postStream.Write(reqBytes8, 0, reqBytes8.Length);
                        postStream.Write(reqBytes9, 0, reqBytes9.Length);
                        postStream.Write(reqBytes10, 0, reqBytes10.Length);
                        postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                        percentComplete += 10;
                        aTaskItem.Progress?.Report(percentComplete);

                        float re = 0;
                        while (size > 0)
                        {
                            if (cancellationToken.IsCancellationRequested)
                            {
                                aTaskItem.TaskStatus = TaskStatusEnum.Cancel;
                                return(false);
                            }
                            postStream.Write(buffer, 0, size);
                            re += ((float)bufferLength) / ((float)length);
                            percentComplete = float.Parse(re.ToString("0.0")) * 70;
                            size            = binaryReader.Read(buffer, 0, bufferLength);
                            aTaskItem.Progress?.Report(percentComplete + 10);
                            //if (re.ToString("0.0") == "0.5")
                            //{
                            //    await Task.Delay(TimeSpan.FromMilliseconds(1), cancellationToken).ConfigureAwait(false);
                            //}
                        }

                        //添加尾部边界
                        postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                        postStream.Close();
                        percentComplete += 10;
                        aTaskItem.Progress?.Report(percentComplete);
                    }
                }
                if (cancellationToken.IsCancellationRequested)
                {
                    aTaskItem.TaskStatus = TaskStatusEnum.Cancel;
                    return(false);
                }
                percentComplete = 90;
                aTaskItem.Progress?.Report(percentComplete);
                aTaskItem.TaskStatus = TaskStatusEnum.OutOfControl;
                //获取服务器端的响应
                using (HttpWebResponse response = (HttpWebResponse)await httpReq.GetResponseAsync())
                {
                    using (Stream receiveStream = response.GetResponseStream())
                    {
                        using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
                        {
                            string returnValue = readStream.ReadToEnd();
                            if (string.IsNullOrEmpty(returnValue))
                            {
                                //percentComplete = 99;
                                //aTaskItem.Progress?.Report(percentComplete);
                                aTaskItem.TaskStatus  = TaskStatusEnum.ErrorCanRetry;
                                aTaskItem.TaskMessage = $"上传接口异常";
                                return(false);
                            }
                            else
                            {
                                JsonHttpReturnBase json = JsonHelper.ConvertFromJsonToObject <JsonHttpReturnBase>(returnValue);
                                if (json.Code != 200)
                                {
                                    //percentComplete = 99;
                                    //aTaskItem.Progress?.Report(percentComplete);
                                    aTaskItem.TaskStatus  = TaskStatusEnum.ErrorCanRetry;
                                    aTaskItem.TaskMessage = $"上传接口异常  {json.Code}  {json.Msg}";
                                    return(false);
                                }
                                else
                                {
                                    percentComplete = 100;
                                    aTaskItem.Progress?.Report(percentComplete);
                                    aTaskItem.TaskStatus = TaskStatusEnum.Completed;
                                    return(true);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    //ignore
                }
                else
                {
                    aTaskItem.TaskStatus  = TaskStatusEnum.ErrorCanRetry;
                    aTaskItem.TaskMessage = ex.Message;
                }
            }
            return(false);
        }