上传图像并使用angularjs保存在本地存储中

时间:2021-02-28 16:48:18

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.

我很想在这里学习angularjs。

2 个解决方案

#1


8  

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

您希望将图像编码为基本64字符串并将其存储在本地存储中。

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.

有关如何将图像转换为基本64字符串的示例,请参阅此答案。 toDataURL()返回一个字符串,然后您可以按照通常将字符串存储在JSON对象中的方式存储。

To display the image, you use something like this:

要显示图像,请使用以下内容:

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

where blahblahblah is the string returned.

blahblahblah是返回的字符串。

#2


1  

Follow below code for upload and save image using AngularJS

使用AngularJS按照以下代码上传和保存图像

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

创建index.php文件并初始化app并创建AngularJS控制器。

<!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.

在此之后,创建app.js并编写代码以使用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.

在此之后,创建post.php文件以将文件上载到存储中。

<?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/

创建图像文件夹。希望这会帮助你。供参考:http://jsfiddle.net/JeJenny/ZG9re/

#1


8  

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

您希望将图像编码为基本64字符串并将其存储在本地存储中。

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.

有关如何将图像转换为基本64字符串的示例,请参阅此答案。 toDataURL()返回一个字符串,然后您可以按照通常将字符串存储在JSON对象中的方式存储。

To display the image, you use something like this:

要显示图像,请使用以下内容:

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

where blahblahblah is the string returned.

blahblahblah是返回的字符串。

#2


1  

Follow below code for upload and save image using AngularJS

使用AngularJS按照以下代码上传和保存图像

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

创建index.php文件并初始化app并创建AngularJS控制器。

<!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.

在此之后,创建app.js并编写代码以使用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.

在此之后,创建post.php文件以将文件上载到存储中。

<?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/

创建图像文件夹。希望这会帮助你。供参考:http://jsfiddle.net/JeJenny/ZG9re/