撰寫 API 或爬蟲時常需要上傳檔案至伺服器,一般寫前端網頁時會在 form
標籤加上 enctype="multipart/form-data"
來指定 ContentType 將資料提交,後端想要模擬的話方法就不一樣了。
我使用的方法是 HttpClient
與 MultipartFormDataContent
做搭配,MultipartFormDataContent
會自動將 ContentType 設為 multipart/form-data
,所以無需再特別設定。
範例程式:
HttpClient hc = new HttpClient(); string url = "http://localhost:63995/Home/Index"; string fileName = "Dapper.XML"; string filePathName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Dapper.XML"); string contentType = MimeMapping.GetMimeMapping(fileName); string stringResult = null; using (var content = new MultipartFormDataContent()) { content.Add(new StringContent("aaa", Encoding.UTF8), "Field_Text_1"); content.Add(new StringContent("bbb", Encoding.UTF8), "Field_Text_2"); Stream fileStream = File.OpenRead(fileName); StreamContent streamContent = new StreamContent(fileStream); streamContent.Headers.Add("Content-Type", contentType); content.Add(streamContent, "Field_File_1", fileName); var postResult = await hc.PostAsync(url, content); stringResult = await postResult.Content.ReadAsStringAsync(); } return stringResult;
執行結果: