Convert filelist into JSON format so that it can be passed as a JSON object along with other data from angular 8 to .net core web api controller.
API call from angular
uploadFiles(document: Document): Observable<Document> {
return this.http.post<Document>(environment.apiEndpoint +"/Upload", document)
.pipe(catchError(this.handleError));
}
model in angular
export class Document {
id: string;
name: string;
files: string;
}
HTML
<div class="row">
<div class="col-md-12">
<input type="file" id="file" accept=".pdf" name="fileInput" multiple
(change)="getFileDetails($event)">
<button type="button" class="btn btn-primary" (click)="uploadFiles()">Upload PDF(s)</button>
</div>
</div>
.ts
getFileDetails(event)
{
this.file = event.target.files;
}
uploadFiles() {
if (this.file.length === 0) {
return;
}
var files = this.file;
this.document.files= Object.assign({},files);
var Data = { ...documentdata, files }
this.service.upload(Data).subscribe(
--------
------)
filelist(this.file):
(2) [File, File]
0: File {name: "PromoTest.pdf", lastModified: 1606692735736, lastModifiedDate: Fri Aug 30 2019
01:44:19 GMT+1100 (Eastern Daylight Time), webkitRelativePath: "", size: 46471, …}
1: File {name: "viewdoctest1.pdf", lastModified: 1604532330799, lastModifiedDate: Mon Oct 25 2020
12:02:25 GMT+1100 (Eastern Daylight Time), webkitRelativePath: "", size: 568912, …}length:
2__proto__: Array(0)
suggestions I tried from google
a = Array.from(theFileList)
a = Array.prototype.slice.call(theFileList)
const fileListAsArray = Array.from(fileList)
const files = [...myFileList]
I have tried different suggestions from google, but everytime I pass it, I get a response code:400 (bad request error)
.net model.
public class UploadDocumentViewModel
{
public string Id{ get; set; }
public string Name { get; set; }
public IEnumerable<IFormFile> Files { get; set; }
}
controller
[HttpPost]
[Route("Upload")]
public async Task<string> Upload([FromBody] UploadDocumentViewModel model)