7

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.

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

6 Comments

First of all thanks. But by doing it would I be able to store this image in an json object? Basically how do I read the content of image?
@AdityaSethi Have expanded upon my answer to cover that
@MatthewDaly, Bro can you please help me if i send this json string to server via http request can i decode this string code again into jpg, png,etc extension too ?? help me out
@Tech Kid You can decode it on the server, but the actual method to do so will obviously depend on the language. If you Google something like "$LANGUAGE_NAME decode base64" you should find something.
@AdityaSethi i have the similar requirements, and i m new to Angular Js. can you please give some sample code, i dont want to create any server, just let user to upload image and i want to save that image locally or if possible to use that further.
|
1

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.