http://www.sufeinet.com/plugin.php?id=keke_group

苏飞论坛

 找回密码
 马上注册

QQ登录

只需一步,快速开始

分布式系统框架(V2.0) 轻松承载百亿数据,千万流量!讨论专区 - 源码下载 - 官方教程

HttpHelper爬虫框架(V2.7-含.netcore) HttpHelper官方出品,爬虫框架讨论区 - 源码下载 - 在线测试和代码生成

HttpHelper爬虫类(V2.0) 开源的爬虫类,支持多种模式和属性 源码 - 代码生成器 - 讨论区 - 教程- 例子

查看: 12056|回复: 3

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

[复制链接]
发表于 2015-6-14 09:18:19 | 显示全部楼层 |阅读模式
以前给大家分享了一个C#/.NET的网络组件–RestSharp,具体请参考:推荐一个.NET(C#)的HTTP辅助类组件–restsharp

今天再给大家示范一下如何应用RestSharp这个网络组件来实现可跨域的文件上传功能。
在文章的末尾我会把这个示例项目的源码下载发布出来。
本项目由一个客户端和一个ASP.NET WEB API 2来演示。客户端主要用于模拟用户的上传文件操作,而WEB API则是来接收用户上传的文件。在这里,我只贴出这两个部分的核心代码。
首先是WEB API(RestSharpUploadFileController.cs):
[C#] 纯文本查看 复制代码
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):
[C#] 纯文本查看 复制代码
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文件如下:
[C#] 纯文本查看 复制代码
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网络组件实现上传文件到远程服务器[源码]】来下载。
最后,如果你喜欢这篇文章,或者是觉得文章内容对你有帮助的话,那就请动动你的手,为我点个赞吧^_^
本文转载至:图享 &#187; C#/.NET RestSharp网络组件实现上传文件到远程服务器【可跨域传文件】



1. 开通SVIP会员,免费下载本站所有源码,不限次数据,不限时间
2. 加官方QQ群,加官方微信群获取更多资源和帮助
3. 找站长苏飞做网站、商城、CRM、小程序、App、爬虫相关、项目外包等点这里
 楼主| 发表于 2015-9-8 10:18:14 | 显示全部楼层
自己顶一下~~~
发表于 2015-9-21 14:26:52 | 显示全部楼层
赞 强烈支持楼主ing……
 楼主| 发表于 2015-9-24 13:47:08 | 显示全部楼层
签约下一站 发表于 2015-9-21 14:26
赞 强烈支持楼主ing……

谢谢,你的支持是我不断努力写文章的最大动力
您需要登录后才可以回帖 登录 | 马上注册

本版积分规则

QQ|手机版|小黑屋|手机版|联系我们|关于我们|广告合作|苏飞论坛 ( 豫ICP备18043678号-2)

GMT+8, 2024-4-29 10:03

© 2014-2021

快速回复 返回顶部 返回列表