Using Vue 3 to send formdata with axios

I've been attempting to upload images to a backend expressjs API using Vue 3. I'm creating a FormData object named "files" and sending it via axios to the server. However, the server isn't receiving anything (req.files is undefined). The server code has been tested successfully with Postman, but it's not working with my Vue code. Here are snippets of the Vue code:

<template>
  <form @submit.prevent="onSubmit">

    <FileSelector v-model="files" :accept="['image/*']">

      <DialogButton>Add</DialogButton>

      <PhotoPreview v-for="file in files" :key="file" :image="file"></PhotoPreview>
    </FileSelector>

    <button type="submit">upload</button>
  </form>
</template>
setup() {
    const files = ref([])
    const axios = inject('axios')
    const { loading, data, error, axiosPostFormData} = useApi('/photo')

    const onSubmit = async () => {
      try {
        const formData = new FormData()
        formData.append("files", files.value)
        console.log(files.value)
        await axiosPostFormData(formData)
      } catch(e) {
        console.log(e)
      }
    }

    return {
      files, onSubmit
    }
  }
}

The Files object appears as this proxy object. Is this correct?

Proxy {0: File}
[[Handler]]: Object
[[Target]]: Array(1)
[[IsRevoked]]: false

When I change it to this, it works.

formData.append("files",  files.value[0])

How can I send multiple files at once?

Answer №1

If you want to append a single file, use

formData.append("files", files.value)
. But for multiple files, you can do it like this:

for (const file of files.value) {
  formData.append('files', file) 
}

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

Creating stylish error labels using Materialize CSS

While Materialize has built-in support for validating input fields like email, I am looking to implement real-time validation for password inputs as well. This would involve dynamically adding error or success labels using JavaScript. Unfortunately, my at ...

Refreshing a data object that is shared among Vue components

I've recently started diving into Vue, and I've found myself responsible for tweaking an existing codebase. There's this data.js file that caught my attention, containing a handful of objects holding city information, like: export default { ...

Leveraging Multiple MongoDB Databases in Meteor.js

Can 2 Meteor.Collections fetch data from separate MongoDB database servers? Dogs = Meteor.Collection('dogs') // mongodb://192.168.1.123:27017/dogs Cats = Meteor.Collection('cats') // mongodb://192.168.1.124:27017/cats ...

Is there a way to display a div element just once in AngularJS?

I only want to print the div once and prevent it from printing again. $scope.printDiv = function(divName) { var printContents = document.getElementById(divName).innerHTML; var popupWin = window.open('', '_blank', 'width=300, ...

What are the steps to create a dynamic website using vuetify?

I am interested in creating an adaptive website using Vuetify: https://vuetifyjs.com/en/ This means there will be multiple versions of the website catered to different devices. An adaptive design will offer various designs for different screen sizes, inc ...

Identify when an ajax request is completed in order to trigger a subsequent ajax request

Within my project, I am faced with a challenge involving select option groups that dynamically load ajax data based on previous selections. The issue arises when I attempt to replicate this functionality for another select option group. Here is the scenar ...

Quickest method for arranging a multi-dimensional array with dates in sequential order

I have a list of appointments with dates and times as shown below: [ ["John Doe", "10 Sep. 2017 2:00 PM"], ["Jane Smith", "10 Sep. 2017 2:00 PM"], ["Alice Johnson", "10 Sep. 2017 1:00 PM"], ["Bob Williams", "10 Sep. 2017 8:00 AM"], ["M ...

The reason why Express is not directing to the static React build files is due to the absence of a specific URL slug

The Scenario Currently, I'm in the process of developing a React application that is being served statically through Express. To clarify, the React app is constructed using npm run build and the resulting static files are stored within the build/ ...

Having trouble with submitting a form using Laravel, Vue, and Inertia?

I encountered an issue with Laravel Vue Inertia while using Bazar from GitHub. Everything was working fine until I attempted to create a new page called Voucher, which was essentially a replica of the Categories page. However, when I tried to create a new ...

Serialize the elements within an array using JSON.stringify

I'm trying to convert an object into a string, but for some reason it's not working correctly: function httpRequest(url) { this.url = url; this.headers = []; } var req = new httpRequest("http://test.com"); req.headers["cookie"] = "version=1 ...

Generating a unique event triggered by element class change

Is it possible to create custom JavaScript events that are triggered when elements receive a specific class? I am trying to monitor all elements within a table and perform certain actions once a particular class is added to them. Can this be done, and if ...

Binding an event to an Angular 2 component directly within its selector code

Looking at my Angular 2 component: import { Component, ElementRef, Renderer } from '@angular/core';; @Component({ selector: 'my-button', templateUrl: 'button.html' }) export class ButtonComponent { private text: string ...

Is there a way to retrieve the client's IP address from the server side within a Next.js application?

How can I determine the user's time zone and location in order to generate a server-side page tailored to their specific location and time zone? I am struggling to retrieve the user's IP address from the request or the localhost IP address (127.0 ...

Connecting Laravel with Express Js

Greetings, I have a technical inquiry. I am proficient in Laravel but relatively new to Express Node. Currently, my code is functioning well with jQuery, but I need to convert it to Express. Should I install Express in the same folder as my Laravel project ...

How can you match the width of a series of elements to the width of an image directly preceding the div?

Looking to ensure that a series of captions have the same width as the images preceding them. This is the HTML code: <div class="theparent"> <img src="pic.jpg"/> <div class="caption"> hello </div> <div> <div ...

Setting up vue-apollo 3.0.0 Beta

Seeking guidance as a newcomer in this field. I have experience with Authentication using Apollo client, but I'm stuck when trying to integrate the new vue-apollo-plugin into my Vue-cli-3 generated project. Specifically, I'm confused about how an ...

Retrieve data from an array of objects nested within another object

Imagine a scenario where there is an object containing an array of objects. let events = { "id": 241, "name": "Rock Party", "type": "party", "days": [ { "i ...

A guide to transforming a string into a numerical value using Vue

When this code is executed, it will display the following string: Pressure 770.3157279 mm <div class="info">Pressure {{info.main.pressure * 0.750064}} mm </div> If you want to convert the number to an integer and achieve the output: Pressure ...

Identifying Angular 2 templates post-file separation: a step-by-step guide

I am currently trying to figure out how to initiate a project in Angular 2 and have encountered an issue. Following the steps outlined in this Angular 2 guide, I was able to separate my .ts files from .js files by configuring my 'temp' directory ...

Get started by setting up and utilizing react version 0.14.0 on your

I'm currently facing an issue in my project while using react-0.14.0. The error message I'm encountering is: Invariant Violation: ReactDOM.render(): Invalid component element. This may be caused by unintentionally loading two independent copie ...