Technical Implementation of Sending Files and JSON in Multipart/Form-Data POST Requests with Axios

Dec 02, 2025 · Programming · 9 views · 7.8

Keywords: Axios | multipart/form-data | JSON | Blob | Content-Type

Abstract: This article provides an in-depth exploration of how to simultaneously send files and JSON data in multipart/form-data POST requests using the Axios library. By analyzing common issues, such as missing Content-Type for JSON parts, it offers a solution based on Blob objects to ensure proper server-side parsing. The paper details core concepts like FormData, Blob, and Axios configuration, with complete code examples and best practices to help developers efficiently handle mixed-data-type network requests.

Introduction

In modern web development, handling mixed requests involving file uploads and structured data (e.g., JSON) is a common requirement. For instance, users may need to submit a form while uploading a file (such as a PDF document) along with related metadata in JSON format. This scenario is prevalent in content management systems, document processing platforms, or multimedia applications. However, when using JavaScript libraries like Axios to send multipart/form-data requests, developers often encounter a critical issue: the Content-Type header for the JSON part may be missing or incorrect, leading to improper parsing on the server side. This article aims to address this by analyzing the root cause and providing a best-practice solution to ensure request integrity and reliability.

Problem Analysis

In the initial implementation, developers use a FormData object to construct the request body, which includes a file field (e.g., PDF) and a JSON string field. A code example is as follows:

doAjaxPost() {
    var formData = new FormData();
    var file = document.querySelector('#file');
    formData.append("file", file.files[0]);
    formData.append("document", documentJson);
    axios({
        method: 'post',
        url: 'http://192.168.1.69:8080/api/files',
        data: formData,
    })
    .then(function (response) {
        console.log(response);
    })
    .catch(function (response) {
        console.log(response);
    });
}

Although this approach seems straightforward, in practice, inspecting the network request via browser developer tools reveals that the file field (e.g., file) has its Content-Type correctly set to application/pdf, while the JSON field (e.g., document) lacks a proper Content-Type or defaults to text/plain;charset=us-ascii. This can cause the server to misinterpret the JSON data as plain text, leading to parsing errors or request failures.

Core Solution

To resolve this issue, the key is to ensure that the JSON part in the multipart request has the correct Content-Type header. Based on best practices, this can be achieved by converting the JSON string into a Blob object. A Blob (Binary Large Object) is a JavaScript object representing immutable raw data, allowing us to specify the MIME type, which automatically sets the corresponding Content-Type when appended to FormData.

Here is an improved code example demonstrating how to correctly implement this solution:

const obj = {
  hello: "world"
};
const json = JSON.stringify(obj);
const blob = new Blob([json], {
  type: 'application/json'
});
const data = new FormData();
data.append("document", blob);
axios({
  method: 'post',
  url: '/sample',
  data: data,
})

In this example, we first create a JavaScript object obj, then convert it to a JSON string using JSON.stringify(). Next, we use the Blob constructor, passing the JSON string as a data array and specifying the type parameter as 'application/json'. The resulting Blob object, when appended to FormData, automatically carries the correct Content-Type header. Finally, the request is sent via Axios, ensuring the server can identify and parse the JSON data.

Technical Details and Extensions

To fully understand this solution, it is essential to delve into several key technical points. First, the FormData interface is used to construct form data and supports appending files, Blobs, or strings. When appending a string, the default Content-Type is text/plain, which explains why the JSON part was mishandled in the original problem. By using a Blob, we can explicitly control the MIME type, avoiding such ambiguity.

Second, the flexibility of Blob objects makes them suitable for various scenarios. Beyond JSON, they can be used for other data types, such as XML or custom binary formats. In practice, if multiple JSON fields or other structured data need to be included in a request, multiple Blob instances can be created and appended to FormData. For example:

const metadata = { author: "John Doe", version: 1 };
const metadataBlob = new Blob([JSON.stringify(metadata)], { type: 'application/json' });
const file = document.querySelector('#file').files[0];
const formData = new FormData();
formData.append("file", file);
formData.append("metadata", metadataBlob);
// Send request...

Additionally, when handling FormData, the Axios library automatically sets the request's Content-Type to multipart/form-data and generates the appropriate boundary string. Developers do not need to manually configure these headers, simplifying the implementation. However, in edge cases, such as custom boundaries or large file handling, further adjustments to Axios configuration or alternative libraries may be necessary.

Best Practices and Considerations

When implementing the above solution, adhering to best practices can enhance code robustness and maintainability. First, always validate input data: ensure JSON objects are valid and handle errors before stringification, e.g., using try-catch blocks for JSON.stringify() exceptions.

Second, consider server-side compatibility. While most modern web frameworks (e.g., Spring Boot, Express.js) correctly parse Blob data in multipart requests, older systems or specific configurations may require additional handling. It is advisable to check the received Content-Type in server logs to ensure consistency with the client.

Finally, performance optimization is also crucial. For large JSON data or files, using Blob may increase memory overhead. In real-world applications, this can be mitigated through streaming or chunked uploads. For instance, for very large files, consider using Axios progress events or specialized file upload libraries.

Conclusion

By encapsulating JSON strings as Blob objects with the correct MIME type, we can effectively resolve the issue of missing Content-Type for JSON parts in Axios multipart/form-data requests. This approach not only improves request reliability but also enhances interoperability with server-side systems. The code examples and technical analysis provided in this article aim to help developers deeply understand the relevant concepts and apply them flexibly in practical projects. As web technologies evolve, the demand for handling mixed-data-type requests will continue to grow, making mastery of these core skills essential for building efficient and stable web applications.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.