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

How can I display a spinner/loader gif when the page loads using Vue?

When it comes to loading components on a webpage, jquery has the options of $( document ).ready() and onload. But in Vue, how can we achieve the same effect? For example, when a user clicks our page, how can we display a spinner until all contents are load ...

Executing npm / http-server script

I'm currently working on a shell script that will compile an Angular app using the "ng build" command and then launch a web server to host the app from the dist folder. The web server will be started with the "http-server" command, which needs to be i ...

Using node.js version 10.0.0 to tinker with gulp

I was working on a node.js api project that functioned perfectly with node.js v8.1.4 & npm v5.0.3. However, upon transitioning to node.js v10.0.0 & npm v5.6.0, I encountered the following error: [email protected] ecosystem E:\opensource& ...

JavaScript not functional, database being updated through AJAX calls

I have created a game using Phaser, a JavaScript library for games. Now I am looking to implement a score table using JS/PHP. My main focus is on transferring a variable from JS to PHP in order to update the database. I have researched numerous topics and ...

How to leverage tsconfig paths in Angular libraries?

While developing an Angular library, I made configurations in the tsconfig.lib.json file by adding the following setup for paths: "compilerOptions": { "outDir": "../../out-tsc/lib", "target": "es2015", "declaration": true, "inlineSources ...

Chrome Extension to Emphasize Every Word

As a novice, I am embarking on the journey of creating my own chrome extension. The idea is to design a popup.html file that showcases a "highlight" button. The functionality would involve clicking this button to highlight all words on the page. Here&apos ...

Unable to cancel the RTK query request

It's quite a dilemma. I need to handle the request differently when there is no user present. I've attempted different approaches like this and that const { data: carts = [] as ICart[], isFetching } = api.useGetCartProductsQuery(user.id, { skip: ...

Manipulating JSON with ng-model in AngularJS

Let's say I have a simple JSON similar to this: { "Object 0": {} } I am trying to display it as a tree structure. This is the approach I am taking: <span>{{key}}</span> // Object 0 <span>{{value}}</span> // {} <ul> ...

Passing NextJS props as undefined can lead to unexpected behavior and

Struggling with dynamically passing props to output different photo galleries on various pages. One of the three props works fine, while the others are undefined and trigger a warning about an array with more than one element being passed to a title elemen ...

In search of the most efficient method for integrating an AJAX-powered TreeGrid feature

Can anyone recommend an Ajax/TreeGrid implementation that meets the following criteria: Must support server side sorting Should be able to load leaf nodes on demand, meaning only children of open nodes are loaded Needs to support paging so that nodes are ...

Combining two elements in a React application

Having a collection of assets and their quantities: const bag = { eth: 50, btc: 30, kla: 10, set: 5, ova: 5 }; const assetList = { eth: { name: "Ethereum", icon: "urlhere", colour: "#030", text: "light&q ...

What is the method to show text on hover in angularjs?

I'm a beginner in AngularJS and I'm looking to show {{Project.inrtcvalue}} when the mouse hovers over values. Can anyone guide me on how to achieve this using AngularJS? <table ng-table="tableParams" show-filter="true" class="table" > ...

Stuffing a container with an image without considering the proportions

I am experimenting with filling a parent <div> with an image without concern for proportions. Despite knowing that it may not look great at all sizes, I just want to test its feasibility. Currently, the image is scaling instead of stretching to fit m ...

Using jQuery to send a GET or POST request directly to a PHP function

I'm seeking some advice. I currently have a search.php file that uses jQuery to retrieve search values input by users. What I'm curious about is if it's feasible to use a jQuery .get JavaScript function to directly call specific PHP function ...

`Datatables sorting feature for British date and time`

I'm currently attempting to organize a column in a table using the DataTables plugin that contains UK date and time formats such as: 21/09/2013 11:15 Implementing Ronan Guilloux's code: jQuery.extend( jQuery.fn.dataTableExt.oSort, { "uk_dat ...

Link scripts can sometimes cause issues with node.js

Greetings! I have successfully created a client-side SPA using vanilla-router. However, my Node.js server sometimes encounters an error when attempting to load a linked script. Uncaught SyntaxError: Unexpected token '<' This error only oc ...

Is it possible to retrieve a physical address using PHP or Javascript?

Is it possible to retrieve the physical address (Mac Address) using php or javascript? I need to be able to distinguish each system on my website as either being on the same network or different. Thank you ...

Finding strikeout text within <s> or <del> tags can be identified by closely examining the HTML codes

The issue arises with the text that reads as follows: 316.6.1 Structures. Structures shall not be constructed This is represented in HTML as: <b> <s> <span style='font-size:10.0pt'>316.6.1 Structures</span> ...

Unresponsive JavaScript on specific element IDs

I'm experimenting with making three lines perform different animations: line 1 rotating 45deg and translating, line 2 becoming opaque, and line 3 rotating -45deg and translating. Check out my JS Fiddle here <a href="#"><div id="menu" onclic ...

`Error encountered in MVC FormsAuthentication post user login`

In my application, I have implemented a login method that successfully communicates with the database and sets the authCookie in version 4.5.1. [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public ActionResult Login(LoginModel model) ...