Compound.js – file uploading

The file uploading process (upload, remove uploaded file etc.) is easy with Node.js and Compound.js. I used ejs template engine and Ubuntu Linux.

1. I added two new routing into the routes.js:

 map.get('upload_form', 'upload_controller#upload_form');  
 map.post('upload_file', 'upload_controller#upload_file');   

2. I added into the app/controllers/upload_controller.js  two new functions:

upload_form – it show upload form.

upload_file – it will handle the uploaded file.

 /**  
  *   
  * show upload form  
  */  
 action('upload_form', function () {   
  render({  
   title: "upload_controller#upload_form"  
  });  
 });  

 /**  
  *   
  * save uploaded file, error handling
  */  
 action('upload_file', function () {   

   var fs = require('fs');  

   this.file_name = req.body.file_name;  
   this.uploaded_file_tmp = req.files.file.path;  
   this.uploaded_file_type = req.files.file.type;  
   this.uploaded_file_name = req.files.file.name;  
   var new_file = "/home/yourhomedir/compound_test/uploaded_files/"+this.uploaded_file_name;  

   fs.rename( this.uploaded_file_tmp, new_file, function(err){  
    if(err) console.log(err);  
     console.log("moved");  
   });  

   console.log(this.uploaded_file_type);  
     render({  
       title: "upload_controller#upload_file"  
   });  
 });  

3. Don’t remember you should create the upload directory and you should set the correct permissions.

 cd compound_test  
 chmod uploaded_files  
 sudo chmod 0777 -R /home/yourhomedir/compound_test/uploaded_files/  

4. I created ejs template files into the /views/upload_controller directory

upload_form.ejs:

 <% var form = formFor('upload_test', {action: 'upload_file', method: 'POST', id: "upload-form", class: 'form-horizontal', enctype: 'multipart/form-data'}) %>  

 <%- form.begin() %>  
   <%- include _form_upload %>  

   <div class="form-actions">  
     <%- form.submit('<i class="icon-ok icon-white"></i> Save & upload file', {class: 'btn btn-primary'}) %>  
   </div>  

 <%- form.end() %>  

_form_upload.ejs:

 <%- form.label('file_name', 'File name') %>   
 <%- form.input('file_name') %>  

 <%- form.label('file', 'File') %>   
 <%- form.file('file') %>  

So, I think that’s it It should be work. 🙂

Advertisements
This entry was posted in Uncategorized and tagged , , , , . Bookmark the permalink.

2 Responses to Compound.js – file uploading

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s