使用multipart form-data方式post数据到服务器

使用multipart/form-data方式提交数据与普通的post方式有一定区别。multipart/form-data的请求头必须包含一个特殊的头信息:Content-Type,其值必须为multipart/form-data。另外还需要规定一个内容分割符用于分割请求体中的多个post的内容,如文件内容和文本内容,只有这样服务端才能正常解析数据。但是,multipart/form-data的基础还是post,它是由post方法来实现的。下面分别给出两种方法提交multipart/form-data数据。

1、使用form表单提交数据

<form action="xx.php" method="post" enctype="multipart/form-data">
   <input type="text" name="uname" class="uname" /><br />
   <input type="text" name="email" class="email" /><br />
   <input type="file" name="file" class="file" /><br />
   <input type="submit" name="submit" value="提交"/>
</form>

form表单提交数据的两种方式。
(1)application/x-www-form-urlencoded 不能用于上传文件,只能提交文本,当然如果有file控件的话也只能提交文件名。
(2)multipart/form-data 用于上传文件。

2、使用HttpClient和MultipartFormDataContent

using (var client = new HttpClient())
using (var content = new MultipartFormDataContent())
{
    client.BaseAddress = new Uri("http://localhost/WapAPIExp/");
    var fileContent1 = new ByteArrayContent(File.ReadAllBytes(@"D:\xx.jpg"));
    fileContent1.Headers.ContentDisposition = new ContentDispositionHeaderValue("file")
    {
        FileName = "xx.jpg"
    };
    var dataContent = new ByteArrayContent(Encoding.UTF8.GetBytes("1"));
    dataContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form")
    {
        Name = "type"
    };
    content.Add(fileContent1);
    content.Add(dataContent);
    var result = client.PostAsync("api/Upload", content).Result;
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值