Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would one handle a file upload with Meteor?

What would be the canonical way to handle a file upload with Meteor?

like image 771
David Avatar asked Apr 11 '12 02:04

David


People also ask

Can we upload file using JavaScript?

html file through a browser, the client will be able to upload a file to the server using Ajax and pure JavaScript. A pure JavaScript file uploader simplifies Ajax based interactions with the server.


3 Answers

I used http://filepicker.io. They'll upload the file, store it into your S3, and return you a URL where the file is. Then I just plop the url into a DB.

  1. Wget the filepicker script into your client folder.

    wget https://api.filepicker.io/v0/filepicker.js
    
  2. Insert a filepicker input tag

    <input type="filepicker" id="attachment">
    
  3. In the startup, initialize it:

    Meteor.startup( function() {
        filepicker.setKey("YOUR FILEPICKER API KEY");
        filepicker.constructWidget(document.getElementById('attachment'));
    });
    
  4. Attach a event handler

    Templates.template.events({
        'change #attachment': function(evt){
            console.log(evt.files);
        }
    });
    
like image 102
jlg_foil Avatar answered Oct 21 '22 14:10

jlg_foil


For images, I use a method similar to Dario's except I don't write the file to disk. I store the data directly in the database as a field on the model. This works for me because I only need to support browsers that support the HTML5 File API. And I only need simple image support.

Template.myForm.events({
  'submit form': function(e, template) {
    e.preventDefault();
    var file = template.find('input type=["file"]').files[0];
    var reader = new FileReader();
    reader.onload = function(e) {
      // Add it to your model
      model.update(id, { $set: { src: e.target.result }});

      // Update an image on the page with the data
      $(template.find('img')).attr('src', e.target.result);
    }
    reader.readAsDataURL(file);
  }
});
like image 26
Harry Love Avatar answered Oct 21 '22 15:10

Harry Love


I've just come up with an implementation of file uploads using Meteor.methods and HTML5 File's API. Let me know what you think.

like image 19
Darío Javier Cravero Avatar answered Oct 21 '22 14:10

Darío Javier Cravero