How To Fix 415 Unsupported Media Type Error while File Upload

How To Fix 415 Unsupported Media Type Error while File Upload

Introduction

In this blog post, we will discuss the common "Unsupported Media Type" error encountered while uploading files to the server along with form data. We will explore the causes of this error and walk through the solutions to resolve it effectively.

Understanding Encoding Types

  • application/x-www-form-urlencoded - This is the default. While sending the form, URL Encoding is performed on the final string consisting of key-value pairs. Some special characters are converted into ASCII characters '%' followed by two hexadecimal digits that can be transmitted over the internet.

  • multipart/form-data - used while uploading files to the server and No character encoding happens As it ensures that in the file binary, no bitstream is altered.

  • text/plain - No encoding happens except spaces.

Now let's understand more with the help of examples-

Uploading Files with Form Data

  1. if you want to upload files along with key values pairs, You can create FormData Object and append values to this object which can be sent in the request body along with Content-Type header is just as follows.

     const formData = getFormData({
           file,
           uniqueKey: key,
           amount: 10,
         });
     axios.post(url, formData, {
             headers: {
               'Content-Type': 'multipart/form-data',
               Authorization: token,
             },
           });
     function getFormData(params: { [s: string]: string | Blob }) {
       let formData = new FormData();
       for (const [key, value] of Object.entries(params)) {
         if (value !== null && value) formData.append(key, value);
       }
       return formData;
     }
    

    The above request will be successfully processed as the file will be sent as binary without any character encoding. But what if you need to send the JSON object in the form data?

     const formData = getFormData({
           file,
           uniqueKey: key,
           requestDetails: JSON.stringify({
                 bucketId: bucket,
                 amount,
                 description,
                 validFrom: new Date(start_date_time),
                 validTo: new Date(end_date_time),
               }),,
         });
     /*
     JSON.stringify you must do for JSON object because formData value 
     type only accepts string/Blob type data
     */
    

    The browser will send the data in multiple parts attaching Content-Type to each byte so that server can identify the content and accordingly parse that. Files data is sent as binary stream and the rest of the form fields are generally treated as "text/plain" but In the case of JSON object Server treats it as a plain string and returns an unsupported media type error. In such a scenario, You need to send content type explicitly on form data values so that the server can understand the type of data It needs to parse.

     const formData = getFormData({
           file,
           uniqueKey: key,
           requestDetails: new Blob(
             [
               JSON.stringify({
                 bucketId: bucket,
                 amount,
                 description,
                 validFrom: new Date(start_date_time),
                 validTo: new Date(end_date_time),
               }),
             ],
             { type: 'application/json' }
           ),
         });
     axios.post(url, formData, {
             headers: {
               Authorization: token,
             },
           });
    

    Here defined the content type of the form request object as application/json and created a Blob-type object which is passed to the server. In the above case, You might not need Content-type: multipart/form-data explicitly as the browser automatically tried to identify the content type of file and dynamically generates the header for you(Though It's browser dependent, In older browsers might not work). If you try to submit the request as above, It should be successfully processed by the server.

Conclusion

Handling content types properly when uploading files with form data is crucial to avoid the "Unsupported Media Type" error. By understanding the different encoding types and setting the correct content type for JSON objects, you can ensure the successful processing of requests on the server.

We hope this blog post helps you tackle similar issues effectively.