The "normal" way of accepting file uploads in Web API is to examine the the Request.Content
. However, I'd like to have the file data be an actual parameter of the method, so that tools like NSwag are able to generate proper TypeScript clients.
So instead of stuff like this:
[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 just want something like this:
public async Task UploadFileInfo(Models.FileInfo fileInfo)
{
//FileInfo contains a string of the binary data, decode it here
}
I have this partly working except that I can't reliably encode the binary file data as a string in JavaScript and then decode it for saving in C#/.NET.
In JavaScript, I've tried FileReader.readAsArrayBuffer
, FileReader.readAsBinaryString
, FileReader.readAsDataURL
, FileReader.readAsText
, but none of these have produced a string of binary data that I can reliably decode. In C#, I've tried System.Text.Encoding.UTF8.GetBytes
and/or Convert.FromBase64String
.
For reference, the relevant code NSwag is generating to communicate with the Web API is as follows:
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
is an Angular HttpClient
.