http://2sharings.com/2015/csharp-net-restsharp-upload-file-to-remote-server-using-restsharp-demo
前给大家分享了一个C#/.NET的网络组件–RestSharp,具体请参考:推荐一个.NET(C#)的HTTP辅助类组件–restsharp
今天再给大家示范一下如何应用RestSharp这个网络组件来实现可跨域的文件上传功能。
在文章的末尾我会把这个示例项目的源码下载发布出来。
本项目由一个客户端和一个ASP.NET WEB API 2来演示。客户端主要用于模拟用户的上传文件操作,而WEB API则是来接收用户上传的文件。在这里,我只贴出这两个部分的核心代码。
首先是WEB API(RestSharpUploadFileController.cs):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Web; using System.Web.Http; namespace RsUploadFileDemo.Web.Controllers { [RoutePrefix("api/upload")] public class RestSharpUploadFileController : ApiController { [Route("rs")] [HttpPost] public HttpResponseMessage Upload() { HttpResponseMessage response = null; var request = HttpContext.Current.Request; if (request.Files.Count > 0) { var fileNameList = new List<string>(); foreach (string file in request.Files) { var f = request.Files[file]; var fileSavePath = HttpContext.Current.Server.MapPath("~/uploads/" + f.FileName); f.SaveAs(fileSavePath); fileNameList.Add(fileSavePath); } response = Request.CreateResponse(HttpStatusCode.OK, fileNameList); } else { response = Request.CreateResponse(HttpStatusCode.BadRequest); } return response; } } } |
其次是客户端(FrmMain.cs):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | privatevoidbtnUpload_Click(objectsender,EventArgse) { varfileLocation=@"D:RestSharp.dll"; try { varrequest=newRestRequest(Method.POST); request.AddFile("file",fileLocation); //calling server with restClient varrestClient=newRestClient{BaseUrl=newUri("http://localhost:57546/api/upload/rs")}; restClient.ExecuteAsync(request,(response)=> { if(response.StatusCode==HttpStatusCode.OK) { MessageBox.Show("上传成功...n"+response.Content); } else { MessageBox.Show(string.Format("出错啦:{0}",response.Content)); } }); } catch(Exceptionex) { MessageBox.Show(string.Format("出错啦:{0}",ex.Message)); } } |
需要注意的另一个问题是:我把WEB API的默认返回类型设置成了JSON格式的,这个设置只需要修改一下Global.asax.cs文件即可,修改后的Global.asax.cs文件如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | usingSystem.Net.Http.Formatting; usingSystem.Net.Http.Headers; usingSystem.Web; usingSystem.Web.Http; namespaceRsUploadFileDemo.Web { publicclassWebApiApplication:HttpApplication { protectedvoidApplication_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(newQueryStringMapping("xml","true","application/xml")); GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(newMediaTypeHeaderValue("text/html")); } } } |
好了,以上就是这个关于使用RestSharp上传文件到远程服务器的示例的
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。