Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload image and save in local storage using angularjs

I want to have a button on my page from where I can upload an image from local system and then I want to save that image in my local storage.

I am keen to learn angularjs here.

like image 862
Aditya Sethi Avatar asked Aug 31 '13 10:08

Aditya Sethi


2 Answers

You'd want to encode the image as a base 64 string and store that in local storage.

See this answer for an example of how to convert the image to a base 64 string. toDataURL() returns a string, which you can then store the same way you would normally store a string in a JSON object.

To display the image, you use something like this:

<img src="data:image/jpeg;base64,blahblahblah"></img>

where blahblahblah is the string returned.

like image 144
Matthew Daly Avatar answered Oct 24 '22 03:10

Matthew Daly


Follow below code for upload and save image using AngularJS

Create index.php file and initialize app and create AngularJS controller.

<!DOCTYPE html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
        <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular-route.min.js"></script>
        <script src="app.js"></script>
    </head>
    <body ng-app="myApp" ng-controller="myCtrl">
        <div>
            <input type="file" file-model="myFile"/>
            <button ng-click="uploadFile()">upload me</button>
        </div>
    </body>
 </html>

After this, Create app.js and write code to upload image using AngularJS.

var myApp = angular.module('myApp', []);

myApp.directive('fileModel', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;

            element.bind('change', function(){
                scope.$apply(function(){
                    modelSetter(scope, element[0].files[0]);
                });
            });
        }
    };
}]);

myApp.service('fileUpload', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, uploadUrl){
        var fd = new FormData();
        fd.append('file', file);
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(){
        })
        .error(function(){
        });
    }
}]);

myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){

    $scope.uploadFile = function(){ 
        var file = $scope.myFile;
        console.log('file is ' + JSON.stringify(file));
        var uploadUrl = "post.php";
        fileUpload.uploadFileToUrl(file, uploadUrl);
    };

}]);

After this, Create post.php file to upload file into storage.

<?php $upload_dir = "images/"; 
if(isset($_FILES["file"]["type"]))
{ 
    $validextensions = array("jpeg", "jpg", "png", "gif");
    $temporary = explode(".", $_FILES["file"]["name"]);
    $file_extension = end($temporary);
    if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg")) && in_array($file_extension, $validextensions)) {
        if ($_FILES["file"]["error"] > 0){
            echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
        } else {
            if (file_exists($upload_dir.$_FILES["file"]["name"])) {                
                echo 'File already exist';
            } else {
                $sourcePath = $_FILES['file']['tmp_name']; // Storing source path of the file in a variable
                $filename = rand().$_FILES['file']['name'];
                $targetPath = $upload_dir.$filename; // Target path where file is to be stored
                move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
                echo 'success';
            }
        }
    } 
} ?>

Create images folder. Hope this will help you. For reference: http://jsfiddle.net/JeJenny/ZG9re/

like image 1
Bhushan Gohel Avatar answered Oct 24 '22 02:10

Bhushan Gohel