Varvara Moiseenko
Varvara Moiseenko

Reputation: 21

Add Custom Header to the FormData/multipart next to Content-disposition

Sending images to the server through multipartform-data with additional headers for each image.

I want to add lang and url custom headers. Each image needs to have personal values in these headers.

Here is an example:

--B_kpXDt398Po5ytQzY0P6SBEM6VmzrsPAAINKJgt
lang: en
url: http://example.com
Content-Disposition: form-data; name="images"; filename="src%5Ctest%5Cresources%5CtestFile.jpeg"
Content-Type: image/jpeg

--B_kpXDt398Po5ytQzY0P6SBEM6VmzrsPAAINKJgt
lang: ru
url: http://anotherExample.com
Content-Disposition: form-data; name="images"; filename="src%5Ctest%5Cresources%5CtestFile.jpeg"
Content-Type: image/jpeg

My current code:

let formData = new FormData();

let options = {
    header: {
      lang: 'en',
      url: 'example.com',
    }
};

// I also tried using these options:
//  let options = {
//      header: '\r\n lang: ru \r\n url: example.com'
//    };

formData.append("images", myImageBlob, options);

I post form with Axios and got this:

------WebKitFormBoundaryqOIB7duTkYj0twQA
Content-Disposition: form-data; name="images"; filename="[object Object]"
Content-Type: image/png

Does anyone have any ideas or clues how to add additional custom headers to formData?

Appreaciate any suggestions

Upvotes: 2

Views: 1801

Answers (1)

kewlashu
kewlashu

Reputation: 1109

One approach for this use case is to have extra meta data form post fields for lang and url

An example of the form:

<form>
    
    <input type="file" name="images[]" multiple>
    <!--for first image-->
    <input type="hidden" name="images_lang[]" value="en">
    <input type="hidden" name="images_url[]" value="example.com">

    <!--for second image-->
    <input type="hidden" name="images_lang[]" value="ru">
    <input type="hidden" name="images_url[]" value="anotherexample.com">
</form>

Upvotes: 2

Related Questions