I know this is very a general question but I am failing to upload a file in Angular 2. I have tried
1) http://valor-software.com/ng2-file-upload/ and
2) http://ng2-uploader.com/home
...but failed. Has anyone uploaded a file in Angular? What method did you use? How to do so? If any sample code or demo link is provided it will be really appreciated.
From the answers above I build this with Angular 5.x
Just call
uploadFile(url, file).subscribe()
to trigger an uploadUse it like this in your component
This is useful tutorial, how to upload file using the ng2-file-upload and WITHOUT ng2-file-upload.
For me it helps a lot.
At the moment, tutorial contains a couple of mistakes:
1- Client should have same upload url as a server, so in
app.component.ts
change lineconst URL = 'http://localhost:8000/api/upload';
to
const URL = 'http://localhost:3000';
2- Server send response as 'text/html', so in
app.component.ts
changeto
I've upload file using reference. No package is required to upload file this way.
// code to be written in .ts file
}
// code to be written in service.ts file
}
// code to be written in html
To upload image with form fields
In my case I needed .NET Web Api in C#
Angular 2 provides good support for uploading file. Any third party library is not required.
using @angular/core": "~2.0.0" and @angular/http: "~2.0.0"
This simple solution worked for me: file-upload.component.html
And then do the upload in the component directly with XMLHttpRequest.
If you are using dotnet core, the parameter name must match the from field name. files in this case:
This answer is a plagiate of http://blog.teamtreehouse.com/uploading-files-ajax
Edit: After uploading, you have to clear the file-upload so that the user can select a new file. And instead of using XMLHttpRequest, maybe it is better to use fetch:
https://github.com/yonexbat/cran/blob/master/cranangularclient/src/app/file-upload/file-upload.component.ts