How to upload files in angular 11, 10, 9, 8 and 7?
Easy way to upload images and documents in angular using ngx-uploader-directive.
The file upload is an essential component to make a form that store some documents and images kind of data. In this tutorial, you’ll learn how to use the angular file upload directive library called ngx-uploader-directive.
The source code for this library is available at GitHub.
The ngx-uploader-directive provides two angular directives, which are ngxFileDrop and ngxFileSelect. Using this directives we can upload files.
Let me tell you that what are the facilities that are provided by this angular library:
- Upload all the selected files in a single request to server
- Upload single file in a single request
- Upload multiple files in a single request
- Upload multiple files in multiple requests(as configured)
- Cancel ongoing requests
- Only allow such types to upload(as configures. for instance, jpg, png, txt, pdf)
- We can also limit the file size for uploading
Let’s walk through how to use ngx-uploader-directive to upload files.
Installation
Add ngx-uploader-directive module as dependency to your project.
npm install ngx-uploader-directive --save
Update
npm update ngx-uploader-directive
Usage
- Import
NgxUploaderDirectiveModule
into yourAppModule
or in a module where you will use it.
or Import NgxUploaderDirectiveModule
into your SharedModule
. This could be useful if your project has nested modules.
- Data structures of Input and upload output events of files
- You can also set Request headers while uploading files like:
const event: IUploadInput = {
type: 'uploadAll',
inputReferenceNumber: Math.random(),
url: this.uploadUrl,
method: 'POST',
data: {
foo: 'bar'
},
headers: { Authorization: 'bearer ' + 'aetklsndfl' }
};
Example
You can always run this working example by cloning this repository and build and run with comman in terminal npm start
.
- Component code
- Html code
- Running demo on local machine
npm install
npm start
Conclusion
Well, I think that’s all for now. If you find any difficulties to use it or any issues with this library feel free to create an issue on GitHub. I’ll try to help as much as I can.
Thanks for reading.