ASP.NET WebApi框架异步实现MultipartContent方式上传文件
作者:作者不详  发布日期:2020-12-15 17:22:45
  ASP.NET WebApi框架异步实现MultipartContent方式上传文件


ASP.NET WebApi框架异步实现MultipartContent方式上传文件|www.csframework.com



ASP.NET WebApi框架异步实现MultipartContent方式上传文件,功能特点:

1. 接口采用异步(Async)方式。
2. 接口支持数据签名。



WebApi服务端接口设计:


C# Code:

/// <summary>
/// 使用MultipartFormData上传文件,支持多个文件上传.
/// 路由格式:http://localhost:8888/user/file/upload
/// </summary>
/// <returns></returns>
[HttpPost]
[ActionName(
"upload")]
public async Task<ModelResponse> Upload()
{
  
//判断内容类型是否MimeMultipartContent
  
if (!this.Request.Content.IsMimeMultipartContent())
  
return new ModelResponse { Code = -1, Message = "无效的媒体类型(必须为MimeMultipartContent)" };
  
  
//获取Request.Headers头部信息
  
string apikey = GetHeaderValue(this.Request.Headers, "apikey");
  
string bucket = GetHeaderValue(this.Request.Headers, "bucket");
  
string sign = GetHeaderValue(this.Request.Headers, "sign");
  
string ts = GetHeaderValue(this.Request.Headers, "ts");
  
  
//检查参数
  
if (String.IsNullOrEmpty(bucket) || String.IsNullOrEmpty(apikey) || String.IsNullOrEmpty(sign))
  
return new ModelResponse { Code = ErrorCodes.InvalidParameter, Message = ErrorCodes.InvalidParameter_Msg };


//
//检查通过,执行逻辑处理。。。。
//

//省略代码。。。。
  
}

//来源:C/S框架网 | www.csframework.com | QQ:23404761



客户端测试接口:


C# Code:


/// <summary>
/// 上传文件
/// URL格式:http://localhost:19893/user/file/upload
/// </summary>
/// <param name="bucket">文件根目录名</param>
/// <param name="fileList">文件清单</param>
/// <param name="headers">提交的Request.Headers数据</param>
/// <returns></returns>
public ModelResponse Upload(string bucket, List<string> fileList, NameValueCollection headers)
{
  
if (headers == null) headers = new NameValueCollection();
  
  
string ts = DateTime.Now.ToString("yyyyMMddHHmmss");
  
  
//传公钥及数据签名
  
headers.Add("apikey", _apikey);
  headers.Add(
"bucket", bucket);
  headers.Add(
"ts", ts);
  headers.Add(
"sign", CryptoHelper.ToMD5(_apikey + bucket + _secretKey + ts));
  
  
using (HttpClient client = new HttpClient())
  {
    client.Timeout
= new TimeSpan(0, 10, 0);//10分钟
    
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/json"));//响应数据格式
    
    
//multipart/form-data的方式上传数据
    
using (var content = new MultipartFormDataContent())
    {
      AddToHeader(content, headers);
//添加FormData
      
AddToContent(content, this.GetFileByteArrayContent(fileList));//添加文件数据
      

      
try
      {
        HttpResponseMessage result
= client.PostAsync(_urlBase, content).Result;//post请求
        
if (result.IsSuccessStatusCode)
        {
          
string json = result.Content.ReadAsStringAsync().Result;//将响应结果显示在文本框内
          
return JsonConvert.DeserializeObject<ModelResponse>(json);
        }
        
else
        {
          
return new ModelResponse { Code = -1, Message = result.Content.ReadAsStringAsync().Result };
        }
      }
      
catch (Exception ex)
      {
        
return new ModelResponse { Code = -1, Message = ex.ToString() };
      }
    }
  }
}

//来源:C/S框架网 | www.csframework.com | QQ:23404761




C# Code:


/// <summary>
/// 添加头部信息
/// </summary>
/// <param name="content"></param>
/// <param name="headers"></param>
private void AddToHeader(MultipartFormDataContent content, NameValueCollection headers)
{
  
foreach (string item in headers.Keys)
  {
    content.Headers.Add(item, headers[item]);
  }
}





C# Code:


/// <summary>
/// 添加内容
/// </summary>
/// <param name="content"></param>
/// <param name="dataContents"></param>
private void AddToContent(MultipartFormDataContent content, List<ByteArrayContent> dataContents)
{
  
foreach (var byteArrayContent in dataContents)
  {
    content.Add(byteArrayContent);
  }
}





C# Code:


/// <summary>
/// 获取文件集合对应的ByteArrayContent集合
/// </summary>
/// <param name="files">文件清单</param>
/// <returns></returns>
private List<ByteArrayContent> GetFileByteArrayContent(List<string> files)
{
  List
<ByteArrayContent> list = new List<ByteArrayContent>();
  
foreach (var file in files)
  {
    
var fileContent = new ByteArrayContent(File.ReadAllBytes(file));
    fileContent.Headers.ContentDisposition
= new ContentDispositionHeaderValue("attachment")
    {
      FileName
= Path.GetFileName(file)
      };
      list.Add(fileContent);
    }
    
return list;
  }
  
  




C# Code:


/// <summary>
/// 获取键值集合对应的ByteArrayContent集合
/// </summary>
/// <param name="collection"></param>
/// <returns></returns>
private List<ByteArrayContent> GetFormDataByteArrayContent(NameValueCollection collection)
{
  List
<ByteArrayContent> list = new List<ByteArrayContent>();
  
foreach (var key in collection.AllKeys)
  {
    
var dataContent = new ByteArrayContent(Encoding.UTF8.GetBytes(collection[key]));
    dataContent.Headers.ContentDisposition
= new ContentDispositionHeaderValue("attachment")
    {
      Name
= key
      };
      list.Add(dataContent);
    }
    
return list;
  }
  
  
//来源:C/S框架网 | www.csframework.com | QQ:23404761





ASP.NET WebApi快速开发框架|APP后端框架-标准版V1.0

适用开发 适用开发:快速搭建APP、B/S、C/S、微信小程序、公众号、Web站点等后端应用服务程序。
运行平台 运行平台:Windows + .NET Framework 4.5
开发工具 开发工具:Visual Studio 2015+,C#语言
数据库 数据库:Microsoft SQLServer 2008R2+(支持多数据库:Oracle/MySql)

ASP.NET WebApi快速开发框架|MVC框架|APP微信小程序后端框架|服务端框架-标准版V1.0




C/S框架网|原创精神.创造价值.打造精品

扫一扫加微信
C/S框架网作者微信 C/S框架网|原创作品.质量保障.竭诚为您服务

上一篇 下一篇