postman上線文件上傳,並用c#服務端接收


一:用postman實現文件上傳,需要配置的地方

  1)參數的配置

  

 

   2)headers的配置

  

 

   3)body的配置       

 

   4)點擊send就可以上傳成功;

 

二: 用c#服務端接收

 public async Task<IHttpActionResult> Test()
        {
            string result = "";
            string url = "";
            List<Stream> listStream = new List<Stream>();
            List<byte[]> listContentByte = new List<byte[]>();
            List<string> listFileName = new List<string>();
            string methodsName = System.Web.HttpContext.Current.Request.QueryString["methodsName"];
            string serverPath = System.Web.HttpContext.Current.Request.QueryString["serverPath"];
            string ArtifactsNum = System.Web.HttpContext.Current.Request.QueryString["ArtifactsNum"];
            string userName = System.Web.HttpContext.Current.Request.QueryString["userName"];
            string guidStr = System.Web.HttpContext.Current.Request.QueryString["guidStr"];
            string routeUrl = System.Web.HttpContext.Current.Request.QueryString["routeUrl"];
            Encoding myEncoding = Encoding.GetEncoding("UTF-8");  //gb2312
            FilesType filesType = FilesType.General;            
            //接收傳遞過來的數據流
            Stream stream = System.Web.HttpContext.Current.Request.InputStream;
            StreamReader reader = new StreamReader(stream, myEncoding);        
            string xml = " ";
            StringBuilder strXML = new StringBuilder();
            while (reader.Peek() >= 0)
            {
                string line = reader.ReadLine().Trim();//直接讀取一行
                if (line == null) return null;
                if (line == String.Empty) continue;
                if (line.StartsWith("<"))
                {
                    xml = line.Trim();
                    strXML.Append(xml);
                }
            } 
            String xmlData = reader.ReadToEnd();
            listStream.Add(stream);
            //byte[] bytes = new byte[stream.Length];
            //stream.Read(bytes, 0, bytes.Length);         
            // 設置當前流的位置為流的開始 
            //stream.Seek(0, SeekOrigin.Begin);
            byte[] bytes = System.Text.Encoding.UTF8.GetBytes(strXML.ToString());
            listContentByte.Add(bytes);
            
            Request.Content.ReadAsStreamAsync().Result.Seek(0, System.IO.SeekOrigin.Begin);       
            ///string content = Request.Content.ReadAsStringAsync().Result;     
            var httpRequest = HttpContext.Current.Request;
            //HttpFileCollection files = HttpContext.Current.Request.Files;
            if (httpRequest.Files.Count > 0)
            {
                foreach (string file in httpRequest.Files)
                {
                    var postedFile = httpRequest.Files[file];
                    listFileName.Add(postedFile.FileName.Split('.')[0]);                                    
                }
            }

                  
            using (HttpClient client = new HttpClient())
            {
                Dictionary<string, string> DicData = new Dictionary<string, string>();
                DicData.Add("MethodName", methodsName);
                DicData.Add("ServerPath", serverPath);
                DicData.Add("ArtifactsNum", ArtifactsNum.ToString());
                DicData.Add("SendTime", DateTime.Now.ToString());
                DicData.Add("UserName", userName);
                DicData.Add("FileType", filesType.ToString());
                DicData.Add("FileGuid", guidStr);
                client.MaxResponseContentBufferSize = 2147483647;
                client.Timeout = TimeSpan.FromMinutes(30);
                MediaTypeWithQualityHeaderValue temp = new MediaTypeWithQualityHeaderValue("application/json") { CharSet = "utf-8" };
                client.DefaultRequestHeaders.Accept.Add(temp);//設定要響應的數據格式
                using (var content = new MultipartFormDataContent())//表明是通過multipart/form-data的方式上傳數據
                {
                    var formDatas = this.GetFormDataByteArrayContent(this.GetNameValueCollection(DicData));//獲取鍵值集合對應
                    var files = this.GetFileByteArray(listContentByte, listFileName);//獲取文件集合對應的ByteArrayContent集合
                    Action<List<ByteArrayContent>> act = (dataContents) =>
                    {//聲明一個委托,該委托的作用就是將ByteArrayContent集合加入到MultipartFormDataContent中
                        foreach (var byteArrayContent in dataContents)
                        {
                            content.Add(byteArrayContent);
                        }
                    };
                    act(formDatas);
                    act(files);//執行act
                    try
                    {
                        url = string.Format(routeUrl + "api/Trading/Files/UploadOptimizeFile");
                        var returnResult = client.PostAsync(url, content).Result;//post請求   
                        if (returnResult.StatusCode == HttpStatusCode.OK)
                            result = returnResult.Content.ReadAsAsync<string>().Result;
                        else
                            result = "30|客戶端連接路由端出錯,錯誤代碼:" + returnResult.StatusCode.ToString();
                    }
                    catch (Exception ex)
                    {
                        result = "29|客戶端連接超時";                 
                    }
                }
            }
            return Ok(result);
        }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM