'How to send multiple files from Ionic/Angular6 to .NET Core API
I think I've spent more time on StackOverflow and other sites these past 2 weeks than I have off of my computer. I've tried multiple Josh Morony and other Ionic pro sites using different file drag/drop upload components, and have tried different combos on the API side with [FromForm], [FromBody], as an object with IList embedded, alone as a single param, etc. and just get nulls.
I've also checked to make sure the name of the file variable 'formFiles' matches as well.
The ONLY time I've seen success is when I used a good 'ol XMLHttpRequest and boom...saw the files on the API right away. Obviously that's not the type of HTTP request I need to use, so any help much appreciated.
upload() {
if (!this.selectedFiles || this.selectedFiles.length === 0) {
this.errorMsg = 'Please choose a file.';
return;
}
const formData = new FormData();
this.selectedFiles.forEach((f) => formData.append('formFiles', f));
let customHeaders = new HttpHeaders();
customHeaders = customHeaders.set('Content-Type', 'multipart/form-data');
const req = new HttpRequest(
'POST',
this.defaultApiUrl + 'ARBs/NewARBs',
formData,
{
headers: customHeaders,
reportProgress: true,
}
);
this.uploading = true;
this.httpClient
.request<CertificateSubmissionResult[]>(req)
.pipe(
finalize(() => {
this.uploading = false;
this.selectedFiles = null;
})
)
.subscribe(
(event) => {
if (event.type === HttpEventType.UploadProgress) {
this.uploadProgress = Math.round(
(100 * event.loaded) / event.total
);
} else if (event instanceof HttpResponse) {
this.submissionResults = event.body as CertificateSubmissionResult[];
}
},
(error) => {
// Here, you can either customize the way you want to catch the errors
throw error; // or rethrow the error if you have a global error handler
}
);
}
and for the API:
[HttpPost]
[Route("api/ARBs/NewARBs")]
[RequestSizeLimit(long.MaxValue)]
public async Task<ActionResult> PostAsync([Required] List<IFormFile> formFiles)
{
var s = "New String";
return Ok();
}
I've also tried it without the multipart/form-data custom header, but that comes across as application/json which is probably not what I want. If someone can be that second pair of eyes and spot what I'm clearly missing I'd surely appreciate it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
