File Upload on ownCloud with Angular js and NodeJs (Express Js)

File Upload on ownCloud with Angular js and NodeJs (Express Js)

Prerequisite
This article assumes that you have already knowledge of AngularJS and Node js.

Required Modules

express, restler, formidable

Ok Lets Go

We will be dividing this into two sections, server side with nodejs and the client end with AngularJS.

Lets have a look at our complete code create index.html and our angular module and controller

index.html

<html>
<head>
  <title>Home</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
  <script type="text/javascript" src="main.js"></script>
</head>
<body ng-app="myApp">
<h1>File Upload on own cloud</h1>
<div ng-controller="myCtrl">
  <form name="uploadForm">
    <input type="file" ng-model="file" onchange="angular.element(this).scope().imageUpload(this.files)">
  </form>
</div>
</body>
</html>

Here we have Included main.js for our angular module and controller. declared our angular app as myApp and We are using controller as ng-controller=”myCtrl”. Named our form as name=”uploadForm”.We have added input type file for select files

main.js

 


angular.module('myApp', [])
    .controller('myCtrl',['$scope','$http','$log',function($scope,$http,$log){
     $scope.imageUpload = function(files){ 
  if(files &amp;&amp; files[0]) {
        var fd = new FormData();
        //Take the first selected file
        fd.append("file", files[0]);
    $http.post('http://localhost:3000/upload', fd, {
   withCredentials: true,
   headers: {'Content-Type': undefined ,'Accept':'application/json'},
   transformRequest: angular.identity
   }).success( function(res){
    $log.log(res);
   }).error( function(err){ $log.log(res);} );
       
      }
 }
    }]);

app.js


var express = require('express'); 
var fs = require('fs');
    var app = express(); 
 var rest = require('restler')
    var bodyParser = require('body-parser');
 var formidable = require('formidable');
    app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "http://localhost");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        next();
    });
    /** Serving from the same express Server
    No cors required */
    app.use(express.static('./public'));
    app.use(bodyParser.json());
   
    /** API path that will upload the files */
    app.post('/upload', function(req, res) {
  //var tokan  = new Buffer(your_username+":"+your_password).toString('base64');
  var form = new formidable.IncomingForm();
        form.parse(req, function (err, fields, files) {
    fs.readFile(files.file.path,function (err,data) {
   if(err){
                 res.json({error_code:1,err_desc:err});
                 return;
            }
   var encodedImage = new Buffer(data, 'binary');
   return;
   rest.put('owncloudApiUrl/remote.php/webdav/dirName/'+files.file.name,{
   headers:{'Authorization' : 'Basic '+ token,
     'Accept' : '*!/!*',
     'Cache-Control':'no-cache',
     'Content-Type': 'application/octet-stream'
   },
   data :encodedImage
    }).on('complete' , function (data) {
   res.send(JSON.stringify(data));
    }).on('err' , function (err) {
   res.json({error_code:1,err_desc:err});
    })
    });
  });
 });
       
    app.listen('3000', function(){
        console.log('running on 3000...');
    });  

Buy a beer for me.!!

 

Leave a Reply

Your email address will not be published. Required fields are marked *