Utilize multipart/form-data to upload several files and retrieve them within Vue.js

My recent project involved uploading a single file using form-data and fetch (POST request) successfully. However, I encountered an issue when trying to upload multiple files. Here is the code snippet in question:

In the HTML part of my vue.js:

<el-button @click="post_visible = true">POST</el-button>
      <el-dialog :visible.sync="post_visible" title="Adding a new value!"> 
                    <span>Image_1</span>
                    <input type="file" name="file1" />
                    <br>
                    <br>

                    <span>Image_2</span>
                    <input type="file" name="file2" />
                    <br>
                    <br>

                    <span>Image_3</span>
                    <input type="file" name="file3" />
                    <br>
                    <br>

                    <el-button @click = "submit"> Submit </el-button>

      </el-dialog>

Now moving on to the Javascript section:

methods:{
submit(){

 var formData = new FormData();
 var fileField = document.querySelector("input[type='file']");

 console.log(fileField.files.length) // Checking the length of the uploaded files.

// Attaching the files.
 formData.append('file', fileField.files[0]); 
 formData.append('file', fileField.files[1]); 
 formData.append('file', fileField.files[2]); 

const headers = new Headers();
            
headers.append('Authorization', 'Bearer '+ token); // Token has been initialized

const body = formData;
const init = {
method: 'POST',
headers,
body
};

fetch('http://*********/****', init)
.then((response) => {
return response.json(); // or .text() or .blob() ...
  })
 .then((text) => {
  // Deal with the response data here
 })
  .catch((e) => {
// Handle any errors that occur
  });
}
}

Upon testing this code, I received a 500 error (internal server error). After successful POST requests using tools like 'AdvancedRestClient', it became apparent that the issue lies in uploading multiple files. By checking the length of fileField.files,I discovered that only one file was being processed instead of three as expected. Further inspection revealed that the formdata object contained only one file and the values for the other two were undefined. It seems there's an error in my code related to handling multiple file uploads. Any guidance or alternative solutions would be greatly appreciated.

Thank you for your assistance.

Answer №1

One element is being returned due to the selector that was used.

If you use document.querySelector, try switching to document.querySelectorAll instead.

Keep in mind that document.querySelectorAll gives back a list/array of nodes, so accessing them will require a different approach.

Best regards, Simon

Hint: When declaring variables, consider using let over var.

Answer №2

Successfully resolved the previous issue by making some modifications to the code. Instead of utilizing document.querySelector, I opted for document.getElementById('file1'). Adjustments were made in both the HTML and JavaScript files. While this may not be the most optimal or efficient way to tackle the problem, it currently provides a functional solution.

The alterations in the HTML segment of the vue.js entail changing the "name" field to the "id" field.

                    <span>Image_1</span>
                    <input type="file" id="file1" />
                    <br>
                    <br>

                    <span>Image_2</span>
                    <input type="file" id="file2" />
                    <br>
                    <br>

                    <span>Image_3</span>
                    <input type="file" id="file3" />
                    <br>
                    <br>

Modifications in the JavaScript file: Replaced document.querySelector with document.getElementById.

var formData = new FormData();
            
const fileField1 = document.getElementById('file1')
const fileField2 = document.getElementById('file2')
const fileField3 = document.getElementById('file3')

formData.append('file', fileField1.files[0]); // attaching the file
formData.append('file', fileField2.files[0]); // attaching the file
formData.append('file', fileField3.files[0]); // attaching the file

// the code for headers, fetch, and POST remains the same.

You can also achieve this using document.getElementsByName. However, personally, I prefer using IDs.

This approach proved effective for me. While not the most elegant solution due to potential issues with readability and scalability when dealing with numerous files, it resolves the current problem at hand.

An optimized solution from someone would be greatly appreciated.

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

Shift all content to the right when viewing on mobile devices

I'm looking to create space for a menu on the left side, similar to the one on Mashable's mobile view. How can I move all the content to the right? Feel free to resize the window and compare with . Thank you. Best regards, Marius ...

Issues with the Tumblr platform's back-to-top button functionality

I am quite comfortable with HTML and CSS, but I'm struggling to make the 'back to top' button work on my Tumblr page. Can someone please give me a hand? I've included some JQuery code to make the text fade in and out when scrolling (inf ...

Implementing hidden parameters in router links with the help of Vuex

Two links are leading to the same component in my code, but I am looking to modify an attribute in my store.js whenever a click event occurs on either of these elements. <router-link :to="'service'" @click="origin(2)"><a class="navigati ...

Bootstrap Carousel unexpectedly leaps to the top of the page while moving forward

I am facing an issue where the slider jumps to the top of the page when I manually advance it. Can anyone provide guidance on how to prevent this from happening? Your help will be greatly appreciated! Below is the code snippet: <div class="row"> ...

Incorporate this form created externally onto my website

I have been working on my website and I am looking to incorporate a form that opens up once the login button is clicked. This form was generated using an online form builder which provides an embed code for seamless integration onto websites. Below, you wi ...

What could be the reason for not just removing the pseudo-class, but instead deleting the entire CSS document altogether?

var style = document.styleSheets[1] style.deleteRule(`.block__header::after`) console.log(`.block__header::after`) What is preventing it from being removed from the CSS document? The pseudo-class is still found in the console, and when trying to dele ...

Experiencing delays with Angular 4 CLI's speed when running ng serve and making updates

After running ng serve, I noticed that the load time is at 34946 ms, which seems pretty slow and is impacting our team's performance. Additionally, when we update our code, it takes too long to reload the page. https://i.sstatic.net/lpTrr.png My Ang ...

Encountering difficulties in importing TailwindCSS

Having trouble importing TailwindCSS and applying CSS? Here's how it's included in my package.json: "devDependencies": { "autoprefixer": "^10.2.4", "css-loader": "^5.1.1", "postc ...

Waiting for a function to finish within a nested function in JavaScript

I'm facing a simple issue that I'm struggling to solve. I have two functions and an object in JavaScript (Node.js) structured like this: var auxmap = new Map(); function one() { for(var i...) { //initialize the map and do something tw ...

Close pop-up upon successful AJAX response in ASP.NET MVC

I have a modal in my view that allows me to create a new record in the database. The view for this functionality is contained within a partial view. Below is the code for the view: <script src="~/Scripts/jquery-3.1.1.js"></script> To han ...

What is the best location to include the sitemap.xml file within a NextJS project?

I recently completed building my NextJS website and utilized an online sitemap generator to create my sitemap.xml file. In the past, when working with ReactJS, I would place it in the public folder, or in the dist folder for projects using regular HTML, CS ...

Set up a custom JavaScript function to automatically refresh a webpage

I am in the process of setting up a JavaScript function to refresh on a specific webpage. The website utilizes an overarching JS and CSS framework, but I desire this particular function to load in a unique manner. The JS function within the framework dyna ...

Incorrect footer navigation on my Vuepress website

I'm in the process of developing a vuepress single page application for showcasing and providing downloads of my personal game projects. When it comes to website navigation, I am aiming to utilize the native sidebar exclusively. This sidebar will hav ...

Retrieving values from all fields in a dynamic form using VuejsLet's say

In the process of developing an admin panel using Vuejs and tailwind CSS for managing exercises on a page, I have encountered some challenges. My current objective is to insert the dynamic form values into a Firebase real-time database. However, I am stru ...

How can I get my ReactJS file to properly show the user's email address?

After clicking submit, I encountered errors in both localhost (3000 and htdocs). When using localhost 3000, upon hitting submit, I was redirected to http://localhost:3000/index.php with the error message: Cannot POST /index.php While in localhost via the ...

Calling synchronous methods in Typescript

Hello Nativescript Team, I seem to be stuck with making method calls in my code. Could you please provide me with guidance on how to implement synchronous method calling in Nativescript + Angular? import { Component, OnInit, AfterContentInit } from " ...

Which should take precedence in a URL: the hash or the querystring?

While some online articles suggest there is no standard for the placement of querystring and hash in a URL, we have continued to observe common practices. This leads to the question: what is the best approach for including both a querystring and hash in th ...

What causes programming languages to exhibit such behavior in the absence of any established hierarchy?

I was puzzled to discover that in Python and Javascript, when using this type of conditional statement, the logic seems off. If we add console.log statements in each condition, it appears that the comparison should be false != true, meaning that the code s ...

displaying li tag depending on the index value within angularjs

I have an HTML structure similar to the following: <div class="main"> <ul> <li ng-repeat='save in saves'> <h3>{{save.name}}</h3> <div > <ul> ...

Unable to get the Gtranslate function to function properly within the drop-down menu

Currently, I am using Gtranslate.io languages on my website with flags displayed without a drop-down menu. Everything is running smoothly but now I am looking to enhance the user experience by placing the flags inside a drop-down list. I want English to ...