使用multipart form-data方式post資料到伺服器
阿新 • • 發佈:2019-02-20
使用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;
}