Wednesday, 5 April 2017

Image Upload with AngularJs and Nodejs

I'm trying to write a form to Insert a New Auction, something like this:

    <form ng-hide="showBid">
Product Name:<br>
<input type="text" name="productTitle" ng-model="productTitle" ><br>


<div ng-show="uploading" class="progress" >
    <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="45" aria-valuemin="0" aria-valuemax="100" style="width: 100%">
        <span class="sr-only"></span>
    </div>
</div>

<label class="btn btn.success">
        <input type="file" file-model="file.upload" name="myfile" ng-disabled="uploading" onchange="angular.element(this).scope().photoChanged(this.files)">
    </label>
    <br>
    <br>
    <img class="mythumbnail" ng-src="">

    <br>
    <br>
    <br>
  <button ng-click="UploadImage()" ng-disabled="uploading" type="submit" class="btn btn-primary">Upload</button>
<br>
<br>

<div ng-show="message">
    <div ng-class="alert"></div>
</div>



Description:<br>
<input type="text" name="description"  ng-model="productDescription" ><br>

Expiration Date:<br>
<input type="date" name="expiration date" ng-model="endtime" ><br>

Minimum Price:<br>
<input type="number" name="minimum price" ng-model="minPrice" > €<br>

Buy-Now Price:<br>
<input type="number" name="buy now" ng-model="productbuynow" >€<br>

<input class="savebutton" type="submit" value="SAVE" ng-click="saveauction(clickToOpen5())"><br>

When i click on save button it saves me the new auction and take me to the invitation form. All works fine without the uploading part, but when i insert this part and i click on the 'Upload' button, it send me the error 'File is not able to be uploaded', that you can see in the index.js below.

this is the index.js when i do the POST req on express

        var multer = require('multer');
        var storage = multer.diskStorage({
              destination: function (req, file, cb) {
                   cb(null, '../uploads/');
        },
              filename: function (req, file, cb) {
                    if(!file.originalname.match(/\.(png|jpg|jpeg)$/)) {
                        var err = new Error();
                         err.code = 'filetype';
                         return cb(err);
                      }
                    else {
                          cb(null, Date.now() + '_' + file.originalname);
                     }

                 }
             });
          var upload = multer({
                  storage: storage,
                  limits: {fileSize: 10000000}
           }).single('myfile');

           app.post('/api/upload', function (req, res) {
    upload(req, res, function (err) {
                if (err) {
                   if(err.code === 'LIMIT_FILE_SIZE'){
                       res.json({ success: false, message: 'File size is too large. Max limit 10MB'});
                }
                   else if (err.code === 'filetype'){
                        res.json({ success: false, message: 'File type is invalid.'});
                }
                   else{
                        res.json({success: false, message: 'File is not able to be uploaded'});
                }
              }
                 else {
                    if(!req.file){
                        res.json({success: false, message: 'No file was selected'});
                 }
                    else{
                        res.json({ success: true, message: 'File uploaded!'});
                 }
               }
            });
         });

This is my controller:

        angular.module('NewAuctionCtrl', ['ngDialog', 'fileModelDirective', 'uploadFileService']).controller('NewAuctionController', ['$scope','$http' ,'ngDialog','uploadFile','$timeout' , function($scope, $http, ngDialog, uploadFile, $timeout){

$scope.file ={};
$scope.message = false;
$scope.alert = '';
$scope.uploading = false;


$scope.UploadImage = function () {

    uploadFile.upload($scope.file).then(function(data) {
        if(data.data.success){
            $scope.uploading = false;
            $scope.alert= 'alert alert-success';
            $scope.message = data.data.message;
            $scope.file = {};
        }
        else {
            $scope.uploading=false;
            $scope.alert ='alert alert-danger';
            $scope.message= data.data.message;
            $scope.file = {};
        }
    });
};

$scope.photoChanged = function (files) {
    if (files.length > 0 && files[0].name.match(/\.(png|jpeg|jpg)$/)) {
        $scope.uploading = true;
        var file = files[0];
        var fileReader = new FileReader();
        fileReader.readAsDataURL(file);
        fileReader.onload = function(e) {
            $timeout(function() {
                $scope.thumbnail = {};
                $scope.thumbnail.dataUrl = e.target.result;
                $scope.uploading = false;
                $scope.message = false;
            });
        };
    } else {
        $scope.thumbnail = {};
        $scope.message = false;
    }
};

this is my service:

         angular.module('uploadFileService', [])

           .service('uploadFile', function ($http) {
              this.upload = function (file) {
                 var fd = new FormData();
                 fd.append('myfile', file.upload);
                 return $http.post('/api/upload', fd, {
                      transformRequest: angular.identity,
                      headers: {'Content-Type': undefined}
                  });

              };

         });

And this is my directive:

           angular.module('fileModelDirective', [])
        .directive('fileModel', ['$parse', function ($parse) {
            return{
               restrict: 'A',
                link: function (scope, element, attrs) {
                    var parsedFile = $parse(attrs.fileModel);
                    var parsefFileSetter = parsedFile.assign;

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

              }
          };

       }]);

There's something wrong with this?



via Marco Pagano

No comments:

Post a Comment