Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send an uploaded image to the server and save it in the server

I want to upload an image and save it in the server. I uploaded the image an got the preview too, but I am stuck in sending that image to the server. I want to send this image to the server using angular services.

This is the html code

<input type="file" fileread="vm.uploadme" />
<img src="{{vm.uploadme}}" width="100" height="50" alt="Image preview...">

This is the directive

(function(){
    angular.module('appBuilderApp').directive("fileread", [function () {
        return {
            scope: {
                fileread: "="
            },
            link: function (scope, element, attributes) {
                element.bind("change", function (changeEvent) {
                    var reader = new FileReader();
                    reader.onload = function (loadEvent) {
                        scope.$apply(function () {
                            scope.fileread = loadEvent.target.result;
                        });
                    }
                    reader.readAsDataURL(changeEvent.target.files[0]);
                });
            }
        }
    }]);
})();
like image 625
shamila Avatar asked Aug 14 '15 11:08

shamila


People also ask

How do I store images on a server?

Store the images as a file in the file system and create a record in a table with the exact path to that image. Or, store the image itself in a table using an "image" or "binary data" data type of the database server.

How do I upload an image to a web server?

Upload using an FTP program or image hosting service. Use your web server's hyperlink function to link your URL. Alternatively, link to the image using the page's HTML code. You must be able to identify the image's permanent location to be able to serve it to your visitors.

How do I upload files to my server?

Right-click the folder and select “Upload other file here. . .“. Browse the server for the file you want to upload. Select the file and click Open. Now, you will see the file in the folder location on the server.


1 Answers

Assuming in the backend you expect Multipart here is a piece of code that has worked for me.

And here is a jsfiddle.

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

app.controller('MyController',

  function MyController($scope, $http) {

    //the image
    $scope.uploadme;

    $scope.uploadImage = function() {
      var fd = new FormData();
      var imgBlob = dataURItoBlob($scope.uploadme);
      fd.append('file', imgBlob);
      $http.post(
          'imageURL',
          fd, {
            transformRequest: angular.identity,
            headers: {
              'Content-Type': undefined
            }
          }
        )
        .success(function(response) {
          console.log('success', response);
        })
        .error(function(response) {
          console.log('error', response);
        });
    }


    //you need this function to convert the dataURI
    function dataURItoBlob(dataURI) {
      var binary = atob(dataURI.split(',')[1]);
      var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
      var array = [];
      for (var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
      }
      return new Blob([new Uint8Array(array)], {
        type: mimeString
      });
    }

  });


//your directive
app.directive("fileread", [
  function() {
    return {
      scope: {
        fileread: "="
      },
      link: function(scope, element, attributes) {
        element.bind("change", function(changeEvent) {
          var reader = new FileReader();
          reader.onload = function(loadEvent) {
            scope.$apply(function() {
              scope.fileread = loadEvent.target.result;
            });
          }
          reader.readAsDataURL(changeEvent.target.files[0]);
        });
      }
    }
  }
]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="MyController">
    <input type="file" fileread="uploadme" />
    <img src="{{uploadme}}" width="100" height="50" alt="Image preview...">
    <br/>
    <p>
      Image dataURI:
      <pre>{{uploadme}}</pre>
    </p>
    <br/>
    <button ng-click="uploadImage()">upload image</button>
  </div>
</div>

Note that the following part:

{
    transformRequest: angular.identity,
    headers: {
        'Content-Type': undefined
    }
}

is some Angular magic, in order for $http to parse FormData and find the correct content-type and so on...

like image 158
Christos Baziotis Avatar answered Oct 15 '22 05:10

Christos Baziotis