-2

How can I upload files using angularjs? I need to upload .xls files so need an extension check and also need to read the data and display it in a table before posting it to PHP server.

Bhumi Singhal
  • 8,063
  • 10
  • 50
  • 76
  • Whats the -1 for ? If you do not know the answer please do not vote down or if you do give a valid reason – Bhumi Singhal Mar 20 '14 at 09:42
  • I didn't downvote, but, you should add more details. What is on the backend? What do you mean by API? A client side API or a server side API? – Jonathan Mar 20 '14 at 09:54
  • 1
    If your question is simply "How can I upload files using angularjs?", there are several duplicates with good answers like this one: http://stackoverflow.com/questions/18571001/file-upload-using-angularjs. Please clarify your specific case or tell us what have you found/tried so far. – glepretre Mar 20 '14 at 10:05

2 Answers2

0

Angular is a client side framework so a file upload is not going to be anything out of the ordinary. At the DOM level it will just use an HTML form with the file input field.

The Angular way would be to write a directive that wraps the upload form.

Angular isn't going to give you anything special for actually saving the file anywhere. Implement something in the backend to receive the file being uploaded. This is such a common requirement that I am sure there is an example out there for whatever language you are using.

There are a couple of directives already written. For example, I used this on a recent project.

Jonathan
  • 5,495
  • 4
  • 38
  • 53
0
## IN HTML : ##

 <input type="file" name="file" id="fileUpload" file-model="myFile" 
  required="required" >
   <button value="Upload" name="submit" class="btn btn-success" ng-
      click="UploadCompanyContact()" title="Click here to upload "  ng-
    hide="uploadCompanyContactForm.myFile.$error.required" >Upload</button>

## IN ANGULAR CONTROLLER : ##
$scope.UploadCompanyContact = function(){
var file = $scope.myFile;
alert(JSON.stringify(file.name));
    var uploadUrl = "/college/upload_company_contact";
    var fd = new FormData();
    fd.append('file', file);    
    $http.post(uploadUrl,fd, {

        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    })
    .success(function(response , status){
        if(response=="true"){
            $.gritter.add({
                text: 'Successfully company contacts  is uploaded',
                class_name: 'gritter-success'
            });
        } else {
            $.gritter.add({
                text: 'Oopss..!! Something went wrong',
                class_name: 'gritter-error'
            });
        }

            $scope.loadCollegeData();
    })
    .error(function(){
        $.gritter.add({
            text: 'Oopss..!! Something went wrong',
            class_name: 'gritter-error'
        });
    });

 ## IN ROUTE(NODEJS): ##
 router.post('/college/upload_company_contact',function(req,res){
 var exceltojson; 
    uploadcsv(req,res,function(err){
        if(err){
                console.log("error"+err);

        }

        if(!req.file){
            console.log("error 1 ");
            return;
        }
         if(req.file.originalname.split('.')
   [req.file.originalname.split('.').length-1] === 'xlsx'){
            exceltojson = xlsxtojson;
        } else {
            exceltojson = xlstojson;
        }
          try {

            exceltojson({
                input: req.file.path,
                output: null, 
                lowerCaseHeaders:true
            }, function(err,result){
                if(err) {

                } 

                var data = result;
                console.log(JSON.stringify(data)+"asdfasdfasdfsdf");

         for(var i=0;i<data.length;i++){

        var newuploadCompanyContact = new uploadCompanyContact();
        newuploadCompanyContact._id= objectID();
        newuploadCompanyContact.college_id=req.user.reference_id;
        newuploadCompanyContact.company_name=data[i].company_name;
        newuploadCompanyContact.company_email=data[i].company_email;
        newuploadCompanyContact.company_contact=data[i].company_contact;
        newuploadCompanyContact.company_address=data[i].company_address;
        newuploadCompanyContact.company_city=data[i].company_city;
        newuploadCompanyContact.company_country=data[i].company_country;

     newuploadCompanyContact.contact_personname=data[i].contact_personname;

   newuploadCompanyContact.contact_personemail=data[i].contact_personemail;


  newuploadCompanyContact.contact_personmobile=data[i].contact_personmobile;


    newuploadCompanyContact.save(function(err,uploadcompany){
    if(err) {console.log("sorry data not inserted 
   :"+err);res.json("false");}
    if(uploadcompany){console.log("data inserted sucessfully : 
 "+uploadcompany);res.json("true");}
     });
    } 

            });
        } catch (e){
           console.log("catchhhhh");
        }

   })
   })

   ## IN MODEL(MONGODB) ##
   var mongoose = require('mongoose');
    var Schema = mongoose.Schema;

   var CollegeCompanySchema = new Schema({
_id: { type: String, unique: true, required: true },
college_id: {type: String},
company_name:{type:String,default:''},
company_email:{type:String,default:''},
company_contact:{type:String,default:''},
company_address:{type:String,default:''},
company_city:{type:String,default:''},
company_country:{type:String,default:''},
contact_personname:{type:String,default:''},
contact_personemail:{type:String,default:''},
contact_personmobile:{type:String,default:''},

});

var collectionName = 'college-company';
var CollegeCompany = module.exports = mongoose.model('CollegeCompany', 
CollegeCompanySchema, collectionName);
module.exports = CollegeCompany;