C#/.NET RestSharp网络组件实现上传文件到远程服务器【可跨域传文件】

以前给大家分享了一个C#/.NET的网络组件–RestSharp,具体请参考:推荐一个.NET(C#)的HTTP辅助类组件–restsharp

今天再给大家示范一下如何应用RestSharp这个网络组件来实现可跨域的文件上传功能。

在文章的末尾我会把这个示例项目的源码下载发布出来。

本项目由一个客户端和一个ASP.NET WEB API 2来演示。客户端主要用于模拟用户的上传文件操作,而WEB API则是来接收用户上传的文件。在这里,我只贴出这两个部分的核心代码。

首先是WEB API(RestSharpUploadFileController.cs):

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):

private void btnUpload_Click(object sender, EventArgs e)
    {
      var fileLocation = @"D:\RestSharp.dll";
      try
      {
        var request = new RestRequest(Method.POST);
        request.AddFile("file", fileLocation);

        //calling server with restClient
        var restClient = new RestClient {BaseUrl = new Uri("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 (Exception ex)
      {
        MessageBox.Show(string.Format("出错啦:{0}", ex.Message));
      }
    }

需要注意的另一个问题是:我把WEB API的默认返回类型设置成了JSON格式的,这个设置只需要修改一下Global.asax.cs文件即可,修改后的Global.asax.cs文件如下:

using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web;
using System.Web.Http;

namespace RsUploadFileDemo.Web
{
  public class WebApiApplication : HttpApplication
  {
    protected void Application_Start()
    {
      GlobalConfiguration.Configure(WebApiConfig.Register);
      GlobalConfiguration.Configuration.Formatters.XmlFormatter.MediaTypeMappings.Add(new QueryStringMapping("xml", "true", "application/xml"));
      GlobalConfiguration.Configuration.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    }
  }
}

好了,以上就是这个关于使用RestSharp上传文件到远程服务器的示例的核心代码了,如果你有兴趣研究一下的话,可以戳【C#/.NET RestSharp网络组件实现上传文件到远程服务器[源码]】来下载。

最后,如果你喜欢这篇文章,或者是觉得文章内容对你有帮助的话,那就请动动你的手,为我点个赞吧^_^

本文同步发布至:图享 » C#/.NET RestSharp网络组件实现上传文件到远程服务器【可跨域传文件】

posted @ 2015-06-14 08:33  Rector  阅读(2137)  评论(0编辑  收藏  举报