Garry Taylor

Garry Taylor

1558165589

Upload File using Angular.JS and Node.JS

We will learn to do file upload with angularjs and nodejs. These can be seen as two separate parts, so for example, if you are working on AngularJS

You are going good with your development work and then you have to do a file upload, oops a hurdle. File upload is not as difficult as some people presume it to be. Well not at-least after this tutorial. Let’s flick the hurdle out of our way.

There are two parts of file upload, the client end where we should enable the user to choose a file and send it to the server. At the server, we receive the file and save it into our desired path.

In this article we will learn to do file upload with angular and node. These can be seen as two separate parts, so for example, if you are working on AngularJS with some other back-end i.e. not Node.js, you can still take help from this article for the angular part of it and vice versa.

Prerequisite

This article assumes you have already worked with AngularJS and Node expressjs and have a basic knowledge of them.

Lets begin

We will be dividing this into two sections, server side with node and the client end with AngularJS.

Backend with NodeJS

We will use multer to handle file upload in our express app. Multer is a popular NodeJS middleware package for handling file uploads. Lets have a look at our complete Server file, I’ll explain parts of it later.

app.js

    var express = require('express');
    var app = express();
    var bodyParser = require('body-parser');
    var multer = require('multer');
    app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "http://localhost");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        next();
    });
    /** Serving from the same express Server
    No cors required */
    app.use(express.static('../client'));
    app.use(bodyParser.json());
    var storage = multer.diskStorage({ //multers disk storage settings
        destination: function (req, file, cb) {
            cb(null, './uploads/')
        },
        filename: function (req, file, cb) {
            var datetimestamp = Date.now();
            cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1])
        }
    });
    var upload = multer({ //multer settings
                    storage: storage
                }).single('file');
    /** API path that will upload the files */
    app.post('/upload', function(req, res) {
        upload(req,res,function(err){
            if(err){
                 res.json({error_code:1,err_desc:err});
                 return;
            }
             res.json({error_code:0,err_desc:null});
        })<br />
    });
    app.listen('3000', function(){
        console.log('running on 3000...');
    });

package.json

    {
      "name": "expapp",
      "version": "1.0.0",
      "description": "",
      "main": "app.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "author": "",
      "license": "ISC",
      "devDependencies": {
        "gulp": "3.9.0",
        "gulp-develop-server": "0.5.0",
        "gulp-jshint": "1.12.0"
      },
      "dependencies": {
        "body-parser": "1.14.1",
        "express": "4.13.3",
        "fs": "0.0.2",
        "multer": "1.1.0"
      }
    }

To install dependencies just run npm install. Alternatively you can install each module independently and save it to your package.json.

Explanation

This section consist explanation of each block of code in our app.js file.

At the top we are requiring our node modules.

app.js

    app.use(function(req, res, next) { //allow cross origin requests
        res.setHeader("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
        res.header("Access-Control-Allow-Origin", "http://localhost");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        next();
    });
    /** Serving from the same express Server
    No cors required */
    app.use(express.static('../client'));
    app.use(bodyParser.json());

Here we are doing two things, we are allowing our express server to accept cross-origin request from another server. (In this case localhost:80)

Alternatively we are asking express to expose client folder as a static path, in this way we can run our AngularJS client code on the same express server (cross-origin wont be required if we follow this).

app.js

    var storage = multer.diskStorage({ //multers disk storage settings
        destination: function (req, file, cb) {
            cb(null, './uploads/')
        },
        filename: function (req, file, cb) {
            var datetimestamp = Date.now();
            cb(null, file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1])
        }
    });

Here we are defining Multer storage settings. Multer supports two type of storage, viz. memory and disk. We are using diskStorage for this tutorial, as memory storage might give problems if the file is too large or multiple files are uploaded very fast.

In the storage setting we give the destination path to save our files. We also rename our file. I’m appending datetime to the name in order to avoid any duplicate naming conflict. Also we need to append the file extension as by default Multer would save the file without any extension.

app.js

    var upload = multer({ //multer settings
                    storage: storage
                }).single('file');

Now we create a Multer instance by calling multer and passing our options into it. At the same time we specify the type of upload, that is, if it ismultiple files or single. In our case its single, and the parameter ('file') should normally be the name of the input field in our html form but in our case since we are using ngFileUpload in AngularJS it should match the key which holds the file object in the post request.

app.js

    /** API path that will upload the files */
    app.post('/upload', function(req, res) {
        upload(req,res,function(err){
            if(err){
                 res.json({error_code:1,err_desc:err});
                 return;
            }
             res.json({error_code:0,err_desc:null});
        })
    });
    app.listen('3000', function(){
        console.log('running on 3000...');
    });

Next we create an express route as '/upload'to upload our file. Multer also provides a callback in which we can check if there was an error while performing upload.

Finally we are creating our express server.

File API

Each uploaded file object contains the following information.

Run Express server

To start the express server, go to your working directory in cmdand run node app.js. I’ll also bundle up the gulpfile.js with the downloaded code, so if you use gulp for automation, you can just start the server by running gulp.

This wraps up the work on backend, now lets move to the front-end stuff.

Front-end in AngularJS

We will be using ng-file-upload module in AngularJS for facilitating file uploads.

Setting Up

Along with angular.js we will need to include ng-file-upload related files into our project.

Install ng-file-upload using a package manager or download the required files form here.

Include the files into your project.

index.html

<script src="angular.min.js"></script>
<script src="ng-file-upload-shim.min.js"></script> <!-- for no html5 browsers support -->
<script src="ng-file-upload.min.js"></script>

Lets have a look at our complete code then I’ll explain each code block in detail. I’ve two files index.html for the markup and main.js for our angular module and controller.

index.html

<html>
    <head>
        <title>Home</title>
    </head>
    <body ng-app="fileUpload">
        <h1>Angular Node File Upload</h1>
        <form  ng-controller="MyCtrl as up" name="up.upload_form">
                Single Image with validations
            <input
               type="file"
               ngf-select
               ng-model="up.file"
               name="file"
               ngf-pattern="'image/*'"
               accept="image/*"
               ngf-max-size="20MB"
               />
            Image thumbnail: <img style="width:100px;" ngf-thumbnail="up.file || '/thumb.jpg'"/>
            <i ng-show="up.upload_form.file.$error.required">*required</i><br>
            <i ng-show="up.upload_form.file.$error.maxSize">File too large
            {{up.file.size / 1000000|number:1}}MB: max 20M</i>
            <button type="submit" ng-click="up.submit()">submit</button>
            <p>{{up.progress}}
        </form>
    </body>
    <script type="text/javascript" src="node_modules/angular/angular.min.js"></script>
    <script type="text/javascript" src="node_modules/ng-file-upload/dist/ng-file-upload.min.js"></script>
    <script type="text/javascript" src="node_modules/ng-file-upload/dist/ng-file-upload-shim.min.js"></script>
    <script type="text/javascript" src="main.js"></script>
</html>

Here we have declared our angular app as fileUpload. We are using controller-as syntax ng-controller="MyCtrl as up". Named our form as name="up.upload_form".

Next, we have added an input type as a file, which will allow us to select files. On top of it, we have added a few directives provided by ng-file-upload, explained as followed.

  • ngf-select

: Shows the type of selection is select. Drag and drop is also available.

  • ngf-pattern

: Partern to match, type of file.(eg:”‘image/*’” for images)

  • ngf-max-size

: Maximum file size allowed to be uploaded.

We have also added ng-model as up.file.

Next, we are displaying the thumbnail of the file selected using the ngf-thumbnail directive.

Below which we have added error-validation messages to display. Finally, we have the submit button and we are also showing the upload progress.

At the bottom the libraries are loaded and our angular app file main.js.

main.js

main.js
    angular.module('fileUpload', ['ngFileUpload'])
    .controller('MyCtrl',['Upload','$window',function(Upload,$window){
        var vm = this;
        vm.submit = function(){ //function to call on form submit
            if (vm.upload_form.file.$valid && vm.file) { //check if from is valid
                vm.upload(vm.file); //call upload function
            }
        }
        vm.upload = function (file) {
            Upload.upload({
                url: 'http://localhost:3000/upload', //webAPI exposed to upload the file
                data:{file:file} //pass file as data, should be user ng-model
            }).then(function (resp) { //upload function returns a promise
                if(resp.data.error_code === 0){ //validate success
                    $window.alert('Success ' + resp.config.data.file.name + 'uploaded. Response: ');
                } else {
                    $window.alert('an error occured');
                }
            }, function (resp) { //catch error
                console.log('Error status: ' + resp.status);
                $window.alert('Error status: ' + resp.status);
            }, function (evt) {
                console.log(evt);
                var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
                console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
                vm.progress = 'progress: ' + progressPercentage + '% '; // capture upload progress
            });
        };
    }]);

Here we have created our app module and defined our controller.

Inject ngFileUpload as a dependency into our app. ngFileUploadprovides an Uploadservice which we need to inject into our controller. We store the controller instance in vm.

vm.submit() is the function called on submit of the form. This function validates the form and in turn calls vm.upload().

The Upload service exposes and upload method, which accepts the web API url and other data. data object should contain the file model to be uploaded. Note the key in the data object that holds the file must match the parameter in your multer’s single file instance.

In our example its file at both places.

We are also calculating and storing the file upload progress in vm.progress variable.

This was it for our client-end implementation, you can run the client app on any localserver or the same express server, see below.

Running our App

Note. These steps may vary if you are not following the same directory structure, ours is as follows, also this structure is only for demonstration purpose, we don’t recommend following it.

Directory Structure

./
    client/
        node_modules/
        index.html
        main.js
    server/
        node_modules/
        app.js
        package.json

Steps to run the demo app.

  • Download the code from here OR clone our repository by running git clone <a href="https://github.com/rahil471/file-upload-with-angularjs-and-nodejs.git" target="_blank">https://github.com/rahil471/file-upload-with-angularjs-and-nodejs.git</a>
  • Navigate to the server directory in our app using command-line.
  • Run npm install
  • If you use gulp run gulp</kbd> OR simply runnode app.js`
  • Open http://localhost:3000 in your browser

Conclusion

Thus we have seen how to upload files using NodeJS and AngularJS. File Upload is not as difficult as some people assume it to be. This was just a basic example of File upload to point you towards the right direction. Also to note, we have learnt file uploads on both ends(back-end and front-end) and the tutorial of each can be used independently of one another. Eg. You can use Multer file upload with some other front-end framework of your choice similarly you can use ngFileUpload with some other back-end technology of your choice. There is a lot more to file uploads like multiple files, drag and drop, etc. You can know more about it by following our reference links below.

Reference Links

DEMO

DOWNLOAD

#angular-js #node-js

What is GEEK

Buddha Community

Upload File using Angular.JS and Node.JS
Aria Barnes

Aria Barnes

1622719015

Why use Node.js for Web Development? Benefits and Examples of Apps

Front-end web development has been overwhelmed by JavaScript highlights for quite a long time. Google, Facebook, Wikipedia, and most of all online pages use JS for customer side activities. As of late, it additionally made a shift to cross-platform mobile development as a main technology in React Native, Nativescript, Apache Cordova, and other crossover devices. 

Throughout the most recent couple of years, Node.js moved to backend development as well. Designers need to utilize a similar tech stack for the whole web project without learning another language for server-side development. Node.js is a device that adjusts JS usefulness and syntax to the backend. 

What is Node.js? 

Node.js isn’t a language, or library, or system. It’s a runtime situation: commonly JavaScript needs a program to work, however Node.js makes appropriate settings for JS to run outside of the program. It’s based on a JavaScript V8 motor that can run in Chrome, different programs, or independently. 

The extent of V8 is to change JS program situated code into machine code — so JS turns into a broadly useful language and can be perceived by servers. This is one of the advantages of utilizing Node.js in web application development: it expands the usefulness of JavaScript, permitting designers to coordinate the language with APIs, different languages, and outside libraries.

What Are the Advantages of Node.js Web Application Development? 

Of late, organizations have been effectively changing from their backend tech stacks to Node.js. LinkedIn picked Node.js over Ruby on Rails since it took care of expanding responsibility better and decreased the quantity of servers by multiple times. PayPal and Netflix did something comparative, just they had a goal to change their design to microservices. We should investigate the motivations to pick Node.JS for web application development and when we are planning to hire node js developers. 

Amazing Tech Stack for Web Development 

The principal thing that makes Node.js a go-to environment for web development is its JavaScript legacy. It’s the most well known language right now with a great many free devices and a functioning local area. Node.js, because of its association with JS, immediately rose in ubiquity — presently it has in excess of 368 million downloads and a great many free tools in the bundle module. 

Alongside prevalence, Node.js additionally acquired the fundamental JS benefits: 

  • quick execution and information preparing; 
  • exceptionally reusable code; 
  • the code is not difficult to learn, compose, read, and keep up; 
  • tremendous asset library, a huge number of free aides, and a functioning local area. 

In addition, it’s a piece of a well known MEAN tech stack (the blend of MongoDB, Express.js, Angular, and Node.js — four tools that handle all vital parts of web application development). 

Designers Can Utilize JavaScript for the Whole Undertaking 

This is perhaps the most clear advantage of Node.js web application development. JavaScript is an unquestionable requirement for web development. Regardless of whether you construct a multi-page or single-page application, you need to know JS well. On the off chance that you are now OK with JavaScript, learning Node.js won’t be an issue. Grammar, fundamental usefulness, primary standards — every one of these things are comparable. 

In the event that you have JS designers in your group, it will be simpler for them to learn JS-based Node than a totally new dialect. What’s more, the front-end and back-end codebase will be basically the same, simple to peruse, and keep up — in light of the fact that they are both JS-based. 

A Quick Environment for Microservice Development 

There’s another motivation behind why Node.js got famous so rapidly. The environment suits well the idea of microservice development (spilling stone monument usefulness into handfuls or many more modest administrations). 

Microservices need to speak with one another rapidly — and Node.js is probably the quickest device in information handling. Among the fundamental Node.js benefits for programming development are its non-obstructing algorithms.

Node.js measures a few demands all at once without trusting that the first will be concluded. Many microservices can send messages to one another, and they will be gotten and addressed all the while. 

Versatile Web Application Development 

Node.js was worked in view of adaptability — its name really says it. The environment permits numerous hubs to run all the while and speak with one another. Here’s the reason Node.js adaptability is better than other web backend development arrangements. 

Node.js has a module that is liable for load adjusting for each running CPU center. This is one of numerous Node.js module benefits: you can run various hubs all at once, and the environment will naturally adjust the responsibility. 

Node.js permits even apportioning: you can part your application into various situations. You show various forms of the application to different clients, in light of their age, interests, area, language, and so on. This builds personalization and diminishes responsibility. Hub accomplishes this with kid measures — tasks that rapidly speak with one another and share a similar root. 

What’s more, Node’s non-hindering solicitation handling framework adds to fast, letting applications measure a great many solicitations. 

Control Stream Highlights

Numerous designers consider nonconcurrent to be one of the two impediments and benefits of Node.js web application development. In Node, at whatever point the capacity is executed, the code consequently sends a callback. As the quantity of capacities develops, so does the number of callbacks — and you end up in a circumstance known as the callback damnation. 

In any case, Node.js offers an exit plan. You can utilize systems that will plan capacities and sort through callbacks. Systems will associate comparable capacities consequently — so you can track down an essential component via search or in an envelope. At that point, there’s no compelling reason to look through callbacks.

 

Final Words

So, these are some of the top benefits of Nodejs in web application development. This is how Nodejs is contributing a lot to the field of web application development. 

I hope now you are totally aware of the whole process of how Nodejs is really important for your web project. If you are looking to hire a node js development company in India then I would suggest that you take a little consultancy too whenever you call. 

Good Luck!

Original Source

#node.js development company in india #node js development company #hire node js developers #hire node.js developers in india #node.js development services #node.js development

Hire Dedicated Node.js Developers - Hire Node.js Developers

If you look at the backend technology used by today’s most popular apps there is one thing you would find common among them and that is the use of NodeJS Framework. Yes, the NodeJS framework is that effective and successful.

If you wish to have a strong backend for efficient app performance then have NodeJS at the backend.

WebClues Infotech offers different levels of experienced and expert professionals for your app development needs. So hire a dedicated NodeJS developer from WebClues Infotech with your experience requirement and expertise.

So what are you waiting for? Get your app developed with strong performance parameters from WebClues Infotech

For inquiry click here: https://www.webcluesinfotech.com/hire-nodejs-developer/

Book Free Interview: https://bit.ly/3dDShFg

#hire dedicated node.js developers #hire node.js developers #hire top dedicated node.js developers #hire node.js developers in usa & india #hire node js development company #hire the best node.js developers & programmers

I am Developer

1597559012

Multiple File Upload in Laravel 7, 6

in this post, i will show you easy steps for multiple file upload in laravel 7, 6.

As well as how to validate file type, size before uploading to database in laravel.

Laravel 7/6 Multiple File Upload

You can easily upload multiple file with validation in laravel application using the following steps:

  1. Download Laravel Fresh New Setup
  2. Setup Database Credentials
  3. Generate Migration & Model For File
  4. Make Route For File uploading
  5. Create File Controller & Methods
  6. Create Multiple File Blade View
  7. Run Development Server

https://www.tutsmake.com/laravel-6-multiple-file-upload-with-validation-example/

#laravel multiple file upload validation #multiple file upload in laravel 7 #multiple file upload in laravel 6 #upload multiple files laravel 7 #upload multiple files in laravel 6 #upload multiple files php laravel

sophia tondon

sophia tondon

1621320738

Angular.JS vs Node.JS || Find the best for your project - Valuecoders

Whether MNCs or Startups, many companies use Angular.JS or Node.JS to develop web applications as these are among the best JavaScript frameworks used for web applications.

According to Statista, Node.JS and Angular.JS are the best frameworks used by developers, with 51.4% and 25.1%, respectively.

Both these frameworks have unique features and advantages, which makes them preferred over the other frameworks.

Many enterprises use these frameworks without even understanding their uniqueness and the type of projects they are suited or made, which is why, today, I will compare some of the best features and advantages of these two frameworks.

So, let’s dive into and learn various things about Angular.JS vs Node.JS without any further delay.

Angular.JS

AngularJS is a fundamental framework for robust web apps. It makes you use HTML as your template language and allows you to spread HTML’s syntax to clearly and succinctly express your application’s components.

AngularJS’s dependency injection & data binding eliminate much of the code you would otherwise have to write. And it all happens within the browser, making it a perfect partner with any server technology.

AngularJS is what HTML would have been having it been designed for applications. HTML is a great declarative language for static documents. It does not contain much in creating applications.

Let’s discuss some main features of Angular.JS and its advantages:

Data Binding

Data binding is probably the most impressive and helpful feature of AngularJS. It will save you from writing a considerable amount of repetitive code.

A typical web application can contain up to 80% of its codebase, dedicated to traversing, manipulating, and listening to the DOM. Data binding makes this code escape so you can concentrate more on your application. Think of your Model as the only source of truth for your application. Your model is where you go to read or update anything in your application.

Data binding directives provide a projection of your Model to the application’s view. This projection is perfect and occurs without any effort on your part.

HTML UI

Another great feature of AngularJS is the fact that it uses the HTML language to build UI. The HTML language is a general and declarative language with concise tags that are easy to understand.

This leads to a more systematic and straightforward UI. JavaScript interfaces are usually more challenging to organize and develop. If you’re looking for a solution that’s fast, easy, and simple to use at a moment’s notice, then this could be it.

Model View Controller (MVC)

MVC is a software design pattern for developing web applications. It is made up of:

Directives allow angular to provide additional functionality with the HTML language. Directives can also be used to “decorate” components with behavior and manipulate DOM attributes in interesting ways. The controller does not need to control the DOM directly, as this must be done through directives.

Directives are a separate part of the set of elements that can be used anywhere other than a web application. The directives provide developers with the element-rich HTML they need to strengthen their online presence.

If you are looking to hire a dedicated angular developer, you can hire an angular js development company.

Node.js is a free and open-source server environment that runs on various platforms(Windows, Linux, Unix, Mac, OS X, etc.). Node.js uses JavaScript on the server.

Node.js is preferred because of its rich library of several JavaScript modules that helps in simplifying web development to a greater extent. Many companies hire Node.js developers for making a NodeJS web application development as it possesses many features.

Read More - https://www.valuecoders.com/blog/technology-and-apps/angular-js-vs-node-js-find-the-best-for-your-project/

#hire nodejs developer #node js development services #hire node js developer #hiring node js developers #hire node js developers #hire dedicated angular js developer

Node JS Development Company| Node JS Web Developers-SISGAIN

Top organizations and start-ups hire Node.js developers from SISGAIN for their strategic software development projects in Illinois, USA. On the off chance that you are searching for a first rate innovation to assemble a constant Node.js web application development or a module, Node.js applications are the most appropriate alternative to pick. As Leading Node.js development company, we leverage our profound information on its segments and convey solutions that bring noteworthy business results. For more information email us at hello@sisgain.com

#node.js development services #hire node.js developers #node.js web application development #node.js development company #node js application