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

Is there a way to filter an array of dates without using the map function when a click

After finally grasping how to pass and retrieve data in React, I encountered an issue. I have a click handler called this.SortASC, and when I click on the title, I want to sort the titles alphabetically. However, I'm having trouble getting this functi ...

The Vue v-for directive encountered an unrecognized property during rendering

Trying to grasp the concept of v-for in Vue JS, especially since I am a newcomer to this framework. Since I am utilizing Django, custom delimiters are necessary. I have a script example that appends a list of objects to a data property: var app = new Vue( ...

Leverage Vue's ability to inject content from one component to another is a

I am currently customizing my admin dashboard (Core-UI) to suit my specific needs. Within this customization, I have an "aside" component where I aim to load MonitorAside.vue whenever the page switches to the Monitor section (done using vue-router). Here ...

"Utilize binding in ReactJS to maintain the correct context

I'm currently learning how to update states in ReactJS by following a tutorial. In the tutorial, I came across this line of code: this.updateLanguage = this.updateLanguage.bind(this). Although I grasp the basics of 'this' and 'bind&apos ...

JavaScript can be used to deactivate the onclick attribute

Is there a way to deactivate one onclick event once the other has been activated? Both divs are initially hidden in the CSS. I'm new to programming, so any help is appreciated. Markup <a id="leftbutton" href="#" onclick="showDiv(this.id); return ...

Expanding the use of tagged template literals for passing additional arguments

Currently, I am utilizing styled-components and creating components through their tagged template literal syntax like this: const Button = styled.button` background-color: papayawhip; border-radius: 3px; color: palevioletred; ` In a specific scenar ...

Ways to trigger a Vue.js method after a delay of 500 milliseconds

Currently, I am developing a search system that triggers an ajax call with every key press. However, I would like to implement a delay of 500ms before the ajax call is made after typing begins. Any ideas on how this can be achieved? ...

Using a Javascript library within an Angular component: A comprehensive guide

I've been working on a Web-Client project that involves visualizing sensor data such as velocity and acceleration within a coordinate system. In order to display this coordinate system, I decided to use the graph.js library from https://github.com/dhu ...

Unable to dispatch actions within the mounted lifecycle hook in Vuex?

Can anyone explain why the json data I fetch with axios is not populating my state.pages as expected? Interestingly, when I make a change to the file and vite reloads, the data appears on the page. However, it disappears again upon refreshing the browser. ...

Struggling to get my JavaScript function for calculating one rep max to work, need some help figuring out the issue

I have been working on a one rep max calculator using the Epley Formula. However, when I try to call the function, it returns as undefined. I have utilized the parameters weight and reps, both of which are parsed as integers, believing that they would be e ...

Is there a method to delay HTTP requests until the number of pending requests drops below a certain threshold (N)?

I'm in the midst of a project that involves allowing users to upload multiple files simultaneously. However, sending out numerous requests all at once can overwhelm the server and trigger a 429 (Too Many Requests) error for those requests. Is there a ...

Guide for making an accordion with a close button that is specific to multiple dynamic IDs

I am looking to create an accordion feature. The idea is that when the user clicks on "Show," the text "Show" should be hidden, and the content along with a "Close" button should be displayed. Then, when the user clicks on "Close," the content and "Close" ...

Unlocking the Secrets of Launching a Modal with Javascript

I currently have an HTML code that includes a fabulous floating button. When I click on this button, I would like to open a modal popup window but unfortunately, I am unsure of how to achieve this. index.html <html> <head> <link rel="s ...

Ways to initiate a transition upon clicking a button, causing it to switch from being hidden (`display: none`) to visible (`display: block`)

I'm attempting to create a smooth transition effect when a button is clicked, similar to a toggle function, where the content below it seamlessly shifts instead of abruptly moving. The classic example of this is the Bootstrap navbar hamburger menu, wh ...

Display a sublist when a list item is clicked

I am receiving a JSON object in my view that looks like this: $scope.mockData = [ { "folder": "folder1", "reports": [{ "name": "report1" }, { "name": "report2" }, { "name": "report3" }] }, { "folder": "folder2", "reports": [{ "name": ...

Preventing the selection of 'None selected' upon dropdown change

When using the NameTextBox Dropdown, all names are available for selection. Upon changing a name and clicking on search, the associated details are retrieved. However, by default, 'None Selected' is displayed. Is there a way to prevent 'None ...

Issue with event binding on datepicker that is dynamically added is not functional

I have integrated the Kendo datepicker into my project, and I am facing an issue with duplicated div elements containing datepickers. The problem is that the datepicker events only fire once on the first duplicated div and then stop working altogether. I ...

When utilizing VueJs, it's not possible to retrieve a data property from within a function

I am encountering a challenge when trying to access the data property within the function. Despite my efforts, I seem to be missing something crucial and unable to pinpoint what it is. Here is my class: export default { name: "Contact", component ...

Using Typescript to iterate through an array of objects and modifying their keys using the forEach method

I have an object called 'task' in my code: const task = ref<Task>({ name: '', description: '', type: undefined, level: 'tactic', participants: undefined, stages: undefined, }); export interface Tas ...

Flow error: Unable to access the value of this.props.width as the property width is not defined in T

In my React Native project, I am utilizing Flow for type checking. For more information, visit: I currently have two files named SvgRenderer.js and Cartoon.js where: Cartoon extends SvgRenderer Below is the source code for both of these files: SvgRend ...