How would one handle a file upload with Meteor?

后端 未结 12 1436
不知归路
不知归路 2020-12-07 07:56

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

12条回答
  •  攒了一身酷
    2020-12-07 08:18

    If you do not require significantly large files or maybe only storing the files for a short period of time then this simple solution works very well.

    In your html...

    
    

    In your template event map...

    Template.template.events({
      'submit': function(event, template){
        event.preventDefault();
        if (window.File && window.FileReader && window.FileList && window.Blob) {
          _.each(template.find('#files').files, function(file) {
            if(file.size > 1){
              var reader = new FileReader();
              reader.onload = function(e) {
                Collection.insert({
                  name: file.name,
                  type: file.type,
                  dataUrl: reader.result
                });
              }
              reader.readAsDataURL(file);
            }
          });
        }
      }
    });
    

    Subscribe to the Collection and in a template render a link...

    {{name}}
    

    While this might not be the most robust or elegant solution for large files or a file intensive application it works very well for all kind of file formats if you want to implement simple upload and download/rendering of the files.

提交回复
热议问题