DEV Community

Md. Khalid Hossen
Md. Khalid Hossen

Posted on • Edited on

1 1 1 1

Multipart-from-data/ file send to backend as json file using axios.

can i send multipart/form-data as json file without converting formdata before sending post request to backend.
Yes, you can do that using axios instance you can send post request without convert your object to form data. After axios versions v0.27.0 automatic your json data as multipart form-data you do not need to take extra pressure for sending binary data.

axios automatic parse json data

You may check my implementaions below where i upload file as json objects.here, in data sections thumbnail is a file type data.

import axios from 'axios';

const postJsonFile = async () => {
  const url = 'https://example.com/api/upload'; 

const data = {
    "title": "Title",
    "thumbnail":  { File {name: 'bkash.jpeg', lastModified: 
        1683520805146, lastModifiedDate: Mon May 08 2023 10:40:05 
        GMT+0600 (Bangladesh Standard Time), webkitRelativePath: 
        '', size: 43133, …}
        length: 
        1[[Prototype]]
        : 
        FileList
      }
    ,
    "description": "<p>Descriptions</p>",
    "skill_level": [
        "BEGINNER",
        "ADVANCE"
    ],
    "demo_videos": [
        "https://youtu.be/PsaXRgCibfU"
    ]
}

  try {
    const response = await axios.post(url, data, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
     formSerializer: {
        // Ensures array indices are included in serialized keys
        indexes: true, 
      },
    });

    console.log('Response:', response.data);
  } catch (error) {
    console.error('Error:', error.response?.data || error.message);
  }
};

postJsonFile();

Enter fullscreen mode Exit fullscreen mode

Note: you may not need to add formSerializer but if your backend written on python during that time you need to serialize data from frontend otherwise it will not works properly Or you may need to added extra code into your backend.

Learn more you may check:

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more