RestSharp 向服务端上传文件用法

客户端代码

var request = new RestRequest(Method.POST);
                            //传递参数
                            request.AddParameter("projectId", "F25F57FC-DD28-4349-AFAD-5797D6B3AF06");
                            //txtPictures.Text为文件路径
                            request.AddFile("file", txtPictures.Text);
                            //calling server with restClient
                            //http://localhost:42352/api/WorkingCondition/Upload 服务端上传方法的接口地址
                            var restClient = new RestClient { BaseUrl = new Uri("http://localhost:42352/api/WorkingCondition/Upload") };
                            restClient.ExecuteAsync(request, async (response) =>
                            {
                                if (response.StatusCode == HttpStatusCode.OK)
                                {
                                    
                                    //返回的路径和文件名集合,格式为["路径","文件名"]
                                    string strResult = response.Content;
                                   
                                }
                                else
                                {
                                  //失败
                                }
                            });

服务端代码

 [HttpPost]
        public HttpResponseMessage Upload()
        {
            HttpResponseMessage response = null;
            var request = HttpContext.Current.Request;
            //获取客户端传过来的参数值
            string projectId = request.Form["projectId"];
            string filePath = "fileupload" + "/" + projectId + "/10";
            if (request.Files.Count > 0)
            {
               
                var fileNameList = new List<string>();
                //request.Files客户端传过来的文件
                foreach (string file in request.Files)
                {
                    var f = request.Files[file];
                    //路径为  fileupload+项目ID+文件类型(10为工况管理)+唯一文件名
                    string fileName = GetUniquelyName() + Path.GetExtension(f.FileName).ToLower();
                    var fileSavePath = HttpContext.Current.Server.MapPath("~/fileupload") + "/"+projectId + "/10"+"/"+fileName;
                    f.SaveAs(fileSavePath);
                    fileNameList.Add(filePath);//文件路径
                    fileNameList.Add(fileName);//改变后的文件名
                }
                response = Request.CreateResponse(HttpStatusCode.OK, fileNameList);
            }
            else
            {
                response = Request.CreateResponse(HttpStatusCode.BadRequest);
            }
            return response;
        }

 

posted @ 2017-11-22 15:40  儿歌三百首  阅读(4254)  评论(0编辑  收藏  举报