C# 使用multipart form | 您所在的位置:网站首页 › button和input紧贴一起 › C# 使用multipart form |
使用multipart/form-data方式提交数据与普通的post方式有一定区别。multipart/form-data的请求头必须包含一个特殊的头信息:Content-Type,其值必须为multipart/form-data。另外还需要规定一个内容分割符用于分割请求体中的多个post的内容,如文件内容和文本内容,只有这样服务端才能正常解析数据。但是,multipart/form-data的基础还是post,它是由post方法来实现的。下面分别给出两种方法提交multipart/form-data数据。 1、使用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; } |
CopyRight 2018-2019 实验室设备网 版权所有 |