I’m currently writing an API where I have to upload documents. To simplify the testing process, I created a small helper file to create the multipart/form-data.
Here is the helper file:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
internal class MultipartFormBuilder | |
{ | |
private MultipartFormDataContent _form = new (); | |
public MultipartFormBuilder() | |
{ | |
} | |
internal MultipartFormBuilder AddFile(string file, string name, string fileName=null) | |
{ | |
var fileContent = new ByteArrayContent(File.ReadAllBytes(file)); | |
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data"); | |
_form.Add(fileContent, name, fileName: fileName ?? file); | |
return this; | |
} | |
internal MultipartFormDataContent Build() | |
{ | |
return _form; | |
} | |
} |
And here is an example on how to use it:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var client=new HttpClient(); | |
var form = new MultipartFormBuilder() | |
.AddFile("document1.docx",name:"document1") | |
.AddFile("document2.docx",name:"document2") | |
.Build(); | |
var response = await client.PostAsync("/upload", form); |