I am trying to upload a file from angular app to c# Web API(essentially to aws s3 bucket through service) with no success, I could use postman to upload files to API which seems to see the filenames in the controller but with Angualar app I always get no files count.
In the network tab and in console I can see form data is posted in request but I dont see anything coming in Controller.
Q) does the file has to be encoded with base 64 and send to API and write the content back into s3?
or can use form-data to post the file to API and save in s3?
Here the code for angular18 and .NET8
upload.component.html:
<div class="card mb-4">
<div class="card-header">
<strong>Upload</strong>
</div>
<div class="card-body">
<div class="upload-section mb-3">
<label for="fileUpload" class="form-label">Select File</label>
<input
type="file"
id="fileUpload"
(change)="onFileSelected($event)"
class="form-control"
multiple
/>
</div>
<div class="d-flex justify-content-end">
<button
type="button"
class="btn btn-primary me-2"
(click)="uploadDocuments()"
>
Upload
</button>
<button
type="button"
class="btn btn-secondary"
(click)="resetDocuments()"
>
Reset
</button>
</div>
</div>
</div>
upload.component.ts
onFileSelected(event: any) {
if (event.target.files && event.target.files.length > 0) {
const files: FileList = event.target.files;
for (let i = 0; i < files.length; i++) {
this.selectedDocuments.push(files[i]);
}
}
}
uploadDocuments() {
if (this.selectedDocuments.length > 0) {
this.uploadProgress = 0; // Reset progress
this.documentService.uploadDocuments(this.selectedDocuments).subscribe({
next: (event) => {
if (event.type === HttpEventType.UploadProgress && event.total) {
this.uploadProgress = Math.round((100 * event.loaded) / event.total);
} else if (event instanceof HttpResponse) {
console.log('Documents uploaded successfully:', event.body);
alert('Documents uploaded successfully!');
this.selectedDocuments = []; // Clear the list after uploading
this.uploadProgress = 0; // Reset progress
}
},
error: (error) => {
console.error('Error uploading documents:', error);
alert('An error occurred during document upload.');
}
});
} else {
alert('There are no documents selected for upload.');
}
}
upload.service.ts
uploadDocuments(files: File[]): Observable<HttpEvent<any>> {
const formData = new FormData();
files.forEach(file => {
formData.append('files', file, file.name);
});
console.log('FormData:', formData); // Just to check the formData contents
formData.forEach((value, key) => {
console.log(`Key: ${key}, Value:`, value);
});
console.log('FormData size:', formData.getAll('files').length);
const req = new HttpRequest('POST', `${this.apiUrl}/documents/upload`, formData, {
reportProgress: true, // Enable progress tracking
responseType: 'json'
});
return this.http.request(req).pipe(
catchError(this.handleError) // Handle errors properly
);
}
Controller:
[HttpPost("upload"), DisableRequestSizeLimit]
public async Task<IActionResult> UploadDocuments([FromForm] IFormFileCollection files)
{
if (files.Count == 0)
{
return BadRequest("No files selected.");
}
await _documentService.UploadDocumentsAsync(files, GetOrganizationName());
return Ok("Files uploaded successfully.");
}