Angular 4 Upload Image to Imgur Get Url
In this Angular Image Upload demo, we will employ the ng2-file-upload library to upload a file to the backend server. We utilize Node.js as a backend server. We install the latest version of Angular using Angular CLI and then start working on thisAngular File Upload demo. If yous are new to Angular, then check out the Athwart Tutorial.
Athwart 12 File Upload Example
To upload a file in Angular, use the ng2-file-upload library. For handling the uploaded files at the backend node.js server, we use the multerlibrary.
Steps to upload epitome in Angular
Follow the below steps.
- Setup an Angular project.
- Install the rxjs-compat library.
- Install bootstrap library.
- Install the ng2-file-upload library.
- Create a node.js backend server and use the multer library.
Step 1: Setup an Athwart Project
At present, set the athwart project using the following command.
ng new ng8fileupload
Now, spin upward the angular app using the following control.
ng serve --open
Step ii: Install rxjs-compat library
So, to fill the gap betweenAthwart and third-party packages, nosotros need to install the rxjs-compat library. That is it.
npm install rxjs-compat --save
Now, y'all volition non get whatever error regarding any rxjs observables.
Pace 3: Install Bootstrap CSS Library
Go to your last and type the following command.
npm install bootstrap --save
At present, include the above file inside the athwart.jsonfile.
"styles": [ "src/styles.css", "./node_modules/bootstrap/dist/css/bootstrap.min.css" ],
It will include the library in the Angular application.
Step four: Install an ng-file-upload library.
Type the following command to install the library.
npm install ng2-file-upload --relieve
Now, write the following code insidean app.module.tsfile.
// app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/cadre'; import { FileSelectDirective } from 'ng2-file-upload'; import { FormsModule } from '@athwart/forms'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent, FileSelectDirective ], imports: [ BrowserModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) consign grade AppModule { } Nosotros take imported the FileSelectDirectivefrom ng2-file-upload.
Likewise, we need to import the FormsModule because nosotros need to write the file upload component to upload a file to the server.
Now, write the following code within anapp.component.tsfile.
// app.component.ts import { Component, OnInit } from '@angular/core'; import { FileUploader, FileSelectDirective } from 'ng2-file-upload/ng2-file-upload'; const URL = 'http://localhost:4000/api/upload'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { championship = 'ng8fileupload'; public uploader: FileUploader = new FileUploader({ url: URL, itemAlias: 'photo' }); ngOnInit() { this.uploader.onAfterAddingFile = (file) => { file.withCredentials = false; }; this.uploader.onCompleteItem = (detail: whatever, response: any, status: any, headers: whatever) => { console.log('ImageUpload:uploaded:', item, condition, response); alert('File uploaded successfully'); }; } } In the to a higher place code, we have importedFileUploaderandFileSelectDirectivefrom ng2-file-upload.
Also, nosotros have divers the backend API URL, which is http://localhost:4000/api/upload.
Nosotros will create a backend server in Node.js and then send a Mail request to the server.
So, here we accept used the Angular Component lifecycle method called ngOnInit().
We have written the file upload code inside thengOnInit function.
At present, the only matter remaining is written the HTML lawmaking for the file upload component.
Write the following piece code inside theapp.component.htmlfile.
<div class="container"> <input blazon="file" name="photo" ng2FileSelect [uploader]="uploader" /> <button type="push button" class="btn btn-success btn-s" (click)="uploader.uploadAll()" [disabled]="!uploader.getNotUploadedItems().length" > Upload an Prototype </push button> </div>
Now, go to the http://localhost:4200/URL and see the output.
Now the only affair remaining is to create a backend in Node.js.
Step v: Create a Node.js server to handle file requests.
First, install the following node modules.
npm install limited multer body-parser dotenv --save
Install nodemon as a dev dependency.
npm install nodemon --salve-dev
Create a new directory inside the root of the angular projection called uploads.
Okay, now create one file in the angular project root folder chosenserver.js.
Write the following piece code inside theserver.jsfile.
// server.js const path = require('path'); const express = crave('express'); const multer = require('multer'); const bodyParser = require('body-parser') const app = express(); const DIR = './uploads'; allow storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, DIR); }, filename: (req, file, cb) => { cb(nothing, file.fieldname + '-' + Date.now() + '.' + path.extname(file.originalname)); } }); permit upload = multer({storage: storage}); app.utilise(bodyParser.json()); app.utilise(bodyParser.urlencoded({extended: true})); app.use(function (req, res, side by side) { res.setHeader('Access-Control-Permit-Origin', 'http://localhost:4200'); res.setHeader('Access-Control-Let-Methods', 'POST'); res.setHeader('Access-Command-Allow-Headers', 'X-Requested-With,content-blazon'); res.setHeader('Admission-Control-Allow-Credentials', truthful); next(); }); app.get('/api', function (req, res) { res.end('file catcher example'); }); app.postal service('/api/upload',upload.single('photo'), office (req, res) { if (!req.file) { panel.log("No file received"); return res.send({ success: false }); } else { console.log('file received'); render res.send({ success: truthful }) } }); const PORT = process.env.PORT || 4000; app.listen(PORT, function () { console.log('Node.js server is running on port ' + PORT); }); First, we have used process.env. Working with environs variables is a great manner to configure dissimilar configurations of your Node.js application.
If the environment variable PORT is divers inside the .env file, information technology will take that variable's value; otherwise, it will pick the value of by default, and in our example, it is 4000.
So node.js volition spin upwards on port 4000.
We take imported themulterlibrary. It is the node.js compatible library for handling files or epitome handling in the node.js.
We tin can store the file using the multer'south file storage function.
When the HTTP Mail request of the file is coming to the node.js server, and so first nosotros have to employ the body-parser module, which parses the request data and and so become to the multer office and extract the file from the request and add the timestamp to the filename and relieve the file inside the uploadsdirectory. So we have already divers the directory.
The final footstep is to showtime the node.js server using the post-obit code.
nodemon server
Now, get to the frontend and endeavor to upload a file. I accept been attempting to upload an image, and it is successfully uploaded. You lot tin can run across the alert() on the front terminate.
This is the primary example of Image Upload in Angular. If you desire to resize the paradigm using node.js, and so check out my Node.js image resize tutorial.
Also, see theuploadsbinder to run into if the prototype is saved or not.
You tin find more than options on ng2-file-upload official documentation.
Finally, Angular File Upload Example is over. Thanks for taking it.
Recommended Posts
Angular HttpClient
Angular Observables
Angular NgFor
Angular NgStyle
Angular NgModel
Athwart NgClass
Source: https://appdividend.com/2019/06/07/angular-8-file-upload-tutorial-with-example-angular-image-upload/
Post a Comment for "Angular 4 Upload Image to Imgur Get Url"