Attempting to send an array of files to a Meteor function

When calling a method within a submit button event, the code looks like this:

'submit #form': function(event, tmpl){
    var files = null;
    if(event.target.fileInput)
        files = event.target.fileInput.files;

    console.log(f);

    Meteor.call('insertFiles', files, function(err){
        if(err)
        {
            console.log(err);
        }
        else
        {
            console.log('insertFiles returned.');
            Router.go('next_screen');
        }
    });
}

The fileInput element is defined as:

<input type="file" name="fileInput" id="fileInput"
       accept="image/jpeg, image/png, application/pdf" multiple/>

The method itself is implemented as follows:

'insertFiles'(files){

    console.log(files);

    //Rest of code.
}

Upon inspecting the client console log, the output for files appears as:

FileList {0: File, 1: File, length: 2}

However, inside the method, the output in the console shows:

{ '0': {}, '1': {} }

This indicates that the files are not being received correctly within the method. To resolve this issue and retrieve the file list properly, what can be done?

Answer №1

It is not possible to simply pass a variable of type FileList or File through DDP to the meteor method.

A straightforward approach would be to utilize FileReader to read file(s) as binary strings and then send it to the server method, which can save it to the filesystem or database.

On the client side:

'submit #form': function(event, tmpl){
  event.preventDefault();

  const fileInput = document.querySelector('#fileInput');
  const files = _.toArray(fileInput.files);

  let cnt = files.length;
  if (!cnt) {
    return;
  }

  const filesArray = [];
  const addFile = (fileObject) => {
    if (fileObject != null) {
      files.push(fileObject);
    }
    if(!(--cnt)) {
      Meteor.call('insertFiles', filesArray, function(err, res){
        ...
      });
    }
  };

  _.each(files, (file) => {
    const reader = new FileReader();
    const name = file.name;
    const type = file.type;
    reader.onload = (ev) => {
      addFile({
        name, type,
        content: ev.target.result
      });
    };
    reader.onerror = () => {
      addFile(null);
    };
    reader.readAsBinaryString(file);
  });
}

Alternatively, you can explore various packages that are designed to assist with uploading and storing files, like CollectionFS.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incomplete DOM elements in jQuery are like puzzles that need to be solved

My issue revolves around jQuery and manipulating DOM elements. I need a specific template setup, as shown below: var threadreply = " <li class='replyItem'>" + " <div class='clearfix'>" + ...

Issues with JQuery .on() occur when functions are passed as arguments

There seems to be a difference in how the .on() function behaves when passing functions as parameters. Interestingly, defining the function inside the parameters versus passing it separately can have different results. An example of this discrepancy is de ...

Achiever.js - Incorporating incremental progress with half stars instead of whole stars

Hello there! I've been utilizing Rater.js in my current project, and so far it has provided me with satisfactory results. However, I have encountered a particular issue that I am struggling to resolve on my own. It would be greatly appreciated if you ...

Allow JavaScript to determine whether to link to an internal or external web address

Currently, I am in the process of setting up a new website and need to create an HTML page with some JavaScript that can determine whether to link to the external or internal IP address. I have researched some JavaScript code to fetch the IP address, whic ...

Arranging JavaScript object by object properties (name)

Can anyone assist me with my training? I am currently learning JavaScript (Js) and TypeScript (Ts) by working with an external public API. After successfully fetching and displaying my data, I now want to implement sorting functionality. My goal is to sor ...

Retrieve an image from the database and associate it with corresponding features or news in PHP

I have retrieved a value from the database, displayed it as an image, and made it a link. So, I want that when a user clicks on the different image, they get the result from the query related to the image. I hope everyone understands. <?php // Connect ...

AngularJs - Customizable dynamic tabs that automatically adapt

Below is the HTML code snippet: <div> <ul data-ng-repeat ="tab in tabs"> <li data-ng-class="{active: tab.selected == 'true'}" message-key="Tab"> </li> </ul> </div> As shown ...

A guide on organizing nested JSON objects in JavaScript

I am currently using JavaScript to retrieve JSON data that looks like this: [{ "data": { "serialNumber": "12345678", "loopCount": 2, "temperature3": 22.74921781259558, "temperature2": 21.459065450414467, "temper ...

Dynamically setting the height of elements using jQuery with incremental values

My Objective: I am trying to dynamically adjust the height of each li element within a ul.container. The goal is to find the tallest li, add 25px to its height, and then apply that new height to all other li elements in the container. This calculation ne ...

Share the name of the Quasar component with the Vue 3 render function

I'm struggling to dynamically create a Vue 3 app with different components specified by name, such as "div", "button", or Quasar's "q-btn". When I try to pass the latter to Vue's render function Vue.h, I encounter difficulties. <html> ...

jQuery does not allow for text input values to be posted

Having an issue with a form using the POST method. I have some PHP controls that are being calculated in jQuery. While all the form control values are accessible in the next form using POST, the values added through jQuery are not posting to the next form. ...

save function ajax failure

I have created a function that adds a row after confirmation. The issue is that after submitting, the tables do not reload and show an error alert. In reality, the data is successfully saved but I need to refresh the page for the table to reload. Below is ...

css failing to load properly following javascript redirection

Upon clicking the button labeled id=cancel, the user will be directed to index.php. $('#cancel').click(function() { if(changes > 0){ $('#dialog-confirm').dialog('open'); }else{ window.location.href = ". ...

Tips for accessing $parent of ng-repeat from ng-include

In my code, I have a nested ng-repeat structure with an ng-include inside the inner ng-repeat. I am trying to access the outer ng-repeat using $parent within the ng-include. Here is an example of what I am working on: index.html <div ng-repeat="popula ...

Enhanced file uploading feature in Firefox 4 using AjaxForm

<form action="upload.aspx" enctype="multipart/form-data" id="ajaxUploadForm" method="post"> <input type="file" name="fileBase" id="fileBase"><input type="submit" value="send" /> </form> $( "#ajaxUploadForm" ).ajaxForm( { iframe: "t ...

Display a div element on the page after 10 seconds of loading

Recently, I managed to get this script working successfully where it fades out within 20 seconds. However, I am looking to modify it so that it takes only 10 seconds to display after the page loads. Any suggestions on what I should change in the code? jQu ...

Encountered a surprise hiccup while attempting to upload file to AWS S3 using browser (putObject

After successfully obtaining a presigned URL through my Node/Express backend for a putObject request on S3, I attempt to upload the relevant files via the browser. However, when making the put request through the browser (or Postman), I encounter a 400 or ...

Creating seamless compatibility between the elliptic library in JavaScript and the ecdsa library in Golang for efficient cross-platform operations

I am having issues with validating a signature created using the elliptic JavaScript library and the ecdsa library from Golang. The elliptic curve in question is secp256k1. Below are some snippets of code: Here are the TypeScript utility functions: impor ...

Using http-proxy to forward request to a different port

In my code, I am creating a proxy that routes all application calls from port 3000 to port 3002 seamlessly. var http = require('http'), httpProxy = require('http-proxy'); var proxy = httpProxy.createProxyServer(); http.create ...

Incorporating library files (css/js) into your app built on the angular-fullstack framework

After using a Yo Angular-Fullstack generator (https://github.com/DaftMonk/generator-angular-fullstack) to start an app, I attempted to install Toastr from bower with the command: bower install angular-toastr Now, I need to add the toastr css and js files ...