I have a question about sending a collection of File
from an Angular 7 application to a .NET Core 3 server.
I have functioning code for sending a single File
to the server. But I have hit a problem when I try to send a collection of File
- i.e: File[]
. This is the controller action:
[HttpPost]
public async Task<IActionResult> Upload([FromForm(Name = "files")] List<IFormFile> files)
{
// implementation...
{
I send FormData
in line with code I have used to send a single file to the server:
const formData = new FormData();
formData.append('files', this.files);
which causes an error with the compiler (see screenshot):
The FormData cannot deal with the collection of File[]
.
If I were to change the same code to handle one single File, for example by choosing the first element in the collection, the File is successfully sent to the server. Like so:
const formData = new FormData();
formData.append('files', this.files[0]);
The request is sent like this:
const httpOptions = {
headers: new HttpHeaders({ 'Content-Disposition' : 'multipart/form-data' }),
};
postPhotos(model: FormData): Observable<any | ErrorReportViewModel> {
return this.http.post('api/Photograph', model, httpOptions)
.pipe(
catchError(error => this.httpErrorHandlerService.handleHttpError(error)));
}
I have also attempted to send the files in the request body with a model. This does not work: the server receives a Null
collection of IFormFile
. My research suggests that sending FormData is the way to go. But the FormData seems not to accept the collection of Files.
How can I send the collection of Files to the server?
You just need to call append method multiple times:
const formData = new FormData();
this.files.forEach((file) => { formData.append('files[]', file); });
Wether the key has to be 'files[]'
or can just be 'files'
depends on the serverside platform that parses the body.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With