Tips for uploading a file using Axios in a form

When uploading a file to a Flask server, I can access files from the flask request global by using raw HTML with the following code:

<form id="uploadForm" action='upload_file' role="form" method="post" enctype=multipart/form-data>
    <input type="file" id="file" name="file">
    <input type=submit value=Upload>
</form>

In Flask:

def post(self):
    if 'file' in request.files:
        ....

However, when trying to achieve the same result with Axios, the flask request global is empty:

<form id="uploadForm" enctype="multipart/form-data" v-on:change="uploadFile">
<input type="file" id="file" name="file">
</form>

uploadFile: function (event) {
    const file = event.target.files[0]
    axios.post('upload_file', file, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
    })
}

If I remove the headers json from the axios.post method in the uploadFile function above, the form key of my flask request object contains a comma-separated list of string values since the file is a .csv. So how can I send a file object via axios?

Answer №1

To upload the file, you need to add it to a formData object and make sure to include the Content-Type header set to multipart/form-data.

let formData = new FormData();
let fileInput = document.querySelector('#file');
formData.append("file", fileInput.files[0]);
axios.post('upload_endpoint', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
})

Answer №2

An example Vue application that needs a local backend server to process requests:

const app = new Vue({
  el: "#app",
  data: {
    file: ''
  },
  methods: {
    submitFile() {
      let formData = new FormData();
      formData.append('file', this.file);
      console.log('>> formData >> ', formData);

      // Requires a backend REST API 
      axios.post('http://localhost:8080/restapi/fileupload',
          formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }
        ).then(function () {
          console.log('SUCCESS!!');
        })
        .catch(function () {
          console.log('FAILURE!!');
        });
    },
    handleFileUpload() {
      this.file = this.$refs.file.files[0];
      console.log('>>>> 1st element in files array >>>> ', this.file);
    }
  }
});

Link to Example

Answer №3

If your API has specific content-type requirements and doesn't accept multipart/formdata, you can opt for an alternative approach to uploading files:

handleFileUpload: function (event) {
    const file = event.target.files[0]
    axios.post('upload_file', file, {
        headers: {
          'Content-Type': file.type
        }
    })
}

Answer №4

Exploring React and working with HTML input elements

Understanding how to create an input field in HTML

<input type="file" onChange={onChange} accept ="image/*"/>

Implementing an onChange listener for the input field

const onChange = (e) => {
  let url = "https://<server-url>/api/upload";
  let file = e.target.files[0];
  uploadFile(url, file);
};

const uploadFile = (url, file) => {
  let formData = new FormData();
  formData.append("file", file);
  axios.post(url, formData, {
      headers: {
        "Content-Type": "multipart/form-data",
      },
    }).then((response) => {
      handleSuccess(response);
    }).catch((error) => {
      handleFail(error);
    });
};

const handleSuccess = (response) => {
  //Implement success handling logic here
};

const handleFail = (error) => {
  //Implement failure handling logic here
};

Answer №5

Hopefully this solution will be useful for others too.

const form = $('#form');
let formData = new FormData(form[0]);
axios.post('your-url', formData)
    .then(response => {
        console.log({response});
    }).catch(error => {
        console.error({error});
    });

Answer №6

Here is the method I prefer:

let data = new FormData(formElement);
//data.append("image", imageFile.files[0]);
const response = await axios.post(
  "link-handle",
  data,
  {
    headers: {
      "Content-Type": "multipart/form-data",
    },
  }
);

Answer №7

Here is a guide on how to upload a file using an object in memory, such as a JSON object:

import axios from 'axios';
import * as FormData  from 'form-data'

async function sendData(jsonData){
    // const payload = JSON.stringify({ hello: 'world'});
    const payload = JSON.stringify(jsonData);
    const bufferObject = Buffer.from(payload, 'utf-8');
    const file = new FormData();

    file.append('upload_file', bufferObject, "b.json");

    const response = await axios.post(
        lovelyURL,
        file,
        headers: file.getHeaders()
    ).toPromise();


    console.log(response?.data);
}

Answer №8

When using Axios version 0.25.0 > up to 0.27.2, there seems to be a problem with handling the FormData object in a PUT request if more than one field has been appended. However, the request works fine when only one field contains a file.

Additionally, starting from Axios version 0.25.0, the correct headers are automatically set, eliminating the need to specify the Content-Type.

Answer №9

When capturing a photo, it is important to save the image and remember its location. Afterwards, retrieve the image's binary large object (blob) from its stored location on the machine. Then, include the blob in a formData object along with the image's name. Finally, send a request with the header set to 'multipart/form-data', causing the image to be found in the backend under 'req.files'.

Answer №10

It took me some time to realize that the error in my controller was due to the actual parameter name... This discovery may assist someone else in a similar situation. I am utilizing Next.js / .Net 6.

Client:

export const test = async (event: any) => {
    const token = useAuthStore.getState().token;
    console.log(event + 'the event')
    if (token) {
        const formData = new FormData();
        formData.append("img", event);
        const res = await axios.post(baseUrl + '/products/uploadproductimage', formData, {
            headers: {
                'Authorization': `bearer ${token}`
            }
        })
        return res
    }
    return null
}

Server:

 [HttpPost("uploadproductimage")]
        public async Task<ActionResult> UploadProductImage([FromForm] IFormFile image)
        {
            return Ok();
        }

The error occurred because the server expected the parameter to be named "image" instead of "img":

formData.append("img", event);

public async Task<ActionResult> UploadProductImage([FromForm] IFormFile image)

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

What is the best way to obtain a user's ID on the server side?

I'm currently working on a node.js application using express and I am in need of retrieving the user ID. I would like to have something similar to "req.userID" so that I can use it in the following way: var counter=0; var user = new Array(); router.g ...

Determine the data type of an object's key

I have a XInterface defined as: export interface XInterface { foo: (() => Foo[]) | Foo[], bar: string, baz: number } When declaring an object using this interface, I want the type of foo to be Foo[], like so: const myObj: XInterface = { ...

What steps should I take in modifying my existing code to use jQuery to set my div to a minimum height rather than a fixed height?

Could someone assist me in adjusting my div to have a min-height instead of a regular height? Whenever I click on the "Learn more" button, it extends past my div because the function is designed to set a specific height rather than an equal height. $.fn.e ...

What is the most effective way to iterate through an array of objects and retrieve the results in a key-value format?

I am dealing with an array of objects that may seem a bit complex initially, but I will simplify it as much as possible. Each object in the array has properties like Engineering, Environment, and others, each containing a sub-object called radars. The rada ...

Struggling to make the fancybox feature function with html/php

I've been trying to find a solution to this problem repeatedly, but I just can't seem to crack it. All I want to do is use fancybox to display an image. Since this is my first time using fancybox, I'm sure someone with more experience will ...

What is the origin of the libraries found in npm-shrinkwrap that do not match the packages listed in package.json?

I'm puzzled by the presence of `express` in my `npm-shrinkwrap` file as a main dependency. Despite this, `express` is not listed as a dependency in my `package.json` file. I can't find any usage of it in my project. It's not included a ...

V5 Modal & jQuery: troubleshooting the spinner problem during loading of content

I'm working on displaying a spinner while loading modal content with the use of bootstrap v5 modal and jQuery. However, I encountered some issues in my example. The spinner does not display again after closing the modal; it only shows for the first t ...

Understanding how flex-wrap property works in flexbox is essential for creating

Take a look at the code snippet below: .flex-container { padding: 20px; margin: 20px; list-style: none; border: 1px solid silver; -ms-box-orient: horizontal; display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -moz- ...

Guidelines for setting up Kendo notifications using an angularjs service

I have successfully defined the Kendo notification in my Angular service. However, when I try to use it with the line uiService.notify.error("You missed some required fields.");, I am getting an error that says "Cannot read property 'show' of nul ...

Issue encountered when making API requests in JavaScript that is not present when using Postman

Currently, I am developing a web application using express and one of the functionalities is exposed through an API with an endpoint on 'api/tone'. This API acts as a wrapper for one of Watson's services but I choose not to call them directl ...

Issue encountered with the Selenium JavaScript Chrome WebDriver

When it comes to testing an application, I always rely on using Selenium chromewebdriver. For beginners like me, the starting point was following this insightful Tutorial: https://code.google.com/p/selenium/wiki/WebDriverJs#Getting_Started After download ...

Variety of properties determined by a "type" prop, expanding variations based on a value from the interface

I am trying to enhance a type based on a value from the main interface. If the type == multiline, it will have a specific interface, and if the type == icon, it will have a different type. import React, { memo, useCallback, ReactNode } from 'react&apo ...

Adapting the column width to display or hide content with CSS styling

I have a row with 2 columns. The left column contains my main content and the right column is a chatroom. I would like users to be able to minimize and open the chatroom, which I already know how to do. However, when the chatroom is open, I want the left ...

Securing WCF in XML-based AJAX service

Is there a way to add security using the http://msdn.microsoft.com/en-us/library/bb472488.aspx resource? Specifically, I am looking to restrict data posting to users from the domain: DOMAIN\User1 and DOMAIN\User2. Thank you. ...

A guide on utilizing webpack devServer proxy within a create react app

Currently, I am in the process of developing a new application with create-react-app and I am looking to incorporate some proxies into my code. In the past, I utilized webpack's devServer for this purpose. module.exports = { ... devServer: { ...

When attempting to dispatch in getServerSideProps, the State refuses to change. Could it be due to the Redux-Next-Wrapper?

I'm facing an issue where the Redux Store does not change when I dispatch in getServerSideProps. Even though I can see the changes in console log after dispatch, the store appears as an empty array when the page loads. Why are these changes not taking ...

Angular Directives in Error

Help needed with creating a custom directive in Angular. Seeking guidance :) I am trying to display the content from 'directive.html' within the 'app-info' directive. The code functions properly without the directive, indicating a mist ...

What method can I use in webpage coding to achieve this special highlight effect, and what is the official term for it?

Need help figuring out how to make an icon change from blue to white when selected. I've searched through Bootstrap, CSS, and HTML, but haven't found the solution yet. Any suggestions would be appreciated! https://i.stack.imgur.com/RK1PD.png ...

The challenge of populating information within a Datalist

In my code snippet, I have a JavaScript function that is used to populate a Datalist: function PopulateDropDown(facility) { $.ajax({ url: '/Rentals/Base/GetContactsForFacility?selectedFacility=' + facility, data: { facility: ...

Can you provide me with a variable that will give me the total size of the scrollbar?

How can I determine the maximum number of pixels scrolled on a webpage? I attempted using window.pageXOffset, but it only gives the current scrolled amount. I require the total size at all times. ...