When working with file uploads in Web API, the common approach is to inspect the Request.Content
. However, I am interested in making the file data an actual parameter of the method. This allows tools like NSwag to generate proper TypeScript clients more efficiently.
Instead of the usual method seen below:
[HttpPost]
public async Task UploadFile()
{
var provider = new MultipartFormDataStreamProvider(Path.GetTempPath());
var result = await Request.Content.ReadAsMultipartAsync(provider);
var formData = result.FormData.GetValues("Path");
...
}
I aim for a simpler solution like this:
public async Task UploadFileInfo(Models.FileInfo fileInfo)
{
//FileInfo contains a string representation of binary data, decode here
}
I have encountered some challenges trying to properly encode the binary file data as a string in JavaScript and then decode it for saving in C#/.NET.
In my JavaScript attempts, I've explored methods such as FileReader.readAsArrayBuffer
, FileReader.readAsBinaryString
, FileReader.readAsDataURL
, and FileReader.readAsText
, but none have provided a consistent output string of binary data for decoding. In C#, I experimented with
System.Text.Encoding.UTF8.GetBytes
and/or Convert.FromBase64String
.
For those interested, NSwag generates the following code to interact with the Web API:
const content_ = JSON.stringify(fileInfo);
let options_ : any = {
body: content_,
observe: "response",
responseType: "blob",
headers: new HttpHeaders({
"Content-Type": "application/json",
})
};
return this.http.request("post", url_, options_)
where this.http
refers to an Angular HttpClient
.