WebApi之服务端,接口创建

服务端接收,并保存图片和文件

仅当 HTTP 请求 Content-Type 值为“multipart/form-data”时,才会填充文件集合。

 postman请求URL:http://localhost:49793/api/Pictures/ReceivePictures

[HttpPost]
public HttpResponseMessage ReceivePictures()
{
    var httpPostedFiles=HttpContext.Current.Request.File;
    if(httpPostedFiles != null)
    {
        for(int i=0;i < httpPostedFiles.Count;i++)
        {
            //保存路径
            string filePath=@"C:\WebPicture\"+ httpPostedFiles[i].FileName;
            httpPostedFiles[i].SaveAs(filePath);
        }
        string jsonres="{\"code\":\"200\",\"message\":\"文件上传成功\"}";
        return new HttpResponseMessage(HttpStatusCode.OK){Content=new StringContent(jsonres,system.Text.Encoding.UTF8,"application/json")};
    }
        return new HttpResponseMessage(HttpStatusCode.NotFound);
}

Posman测试


服务端接收参数

当 HTTP 请求Content-Type值为“application/x-www-form-urlencoded”或“multipart/form-data”时,将Form填充该属性

 postman请求URL:http://localhost:49793/api/Pictures/ReceiveParameters

[HttpPost]
public HttpResponseMessage ReceiveParameters()
{
    NameValueCollection httpPostedParams=HttpContext.Current.Request.Form;
    if(httpPostedParams != null)
    {
        for(int i=0;i < httpPostedParams.Count;i++)
        {
            //可以采用键值对获取内容,也可以使用数组取值
            string strValue=httpPostedParams["123"];
        }
        string jsonres="{\"code\":\"200\",\"message\":\"文件上传成功\"}";
        return new HttpResponseMessage(HttpStatusCode.OK){Content=new StringContent(jsonres,system.Text.Encoding.UTF8,"application/json")};
    }
        return new HttpResponseMessage(HttpStatusCode.NotFound);
}

服务端接收参数

Content-Type的值不同,接收的数据内容也不同,文件和图片会出现乱码,请选择第一种模式

postman请求URL:http://localhost:49793/api/custormers

[Route("api/Custormers")]
[HttpPost]
public HttpResponseMessage ReceiveParameterCustorm()
{
    int iLength=HttpContext.Current.Request.ContentLength;
    if(iLength!= 0)
    {
        byte[] charRec=new byte[iLength];
        HttpContext.Current.Request.InputStream.Read(charRec,0,iLength)
        string strReceive=System.Text.Encoding.UTF8.GetString(charRec,0,iLength);
        //打印到本地
        File.WriteAllText(@"c:\WebPicture\log.txt",strReceive);

        string jsonres="{\"code\":\"200\",\"message\":\"文件上传成功\"}";
        return new HttpResponseMessage(HttpStatusCode.OK){Content=new StringContent(jsonres,system.Text.Encoding.UTF8,"application/json")};
    }
        return new HttpResponseMessage(HttpStatusCode.NotFound);
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值