k6 community forum

Multipart form requests - add headers and batch requests

Is it possible to add a header to a multipart form request (where I’m uploading a file)? My upload is failing because a bespoke request header is missing.

Also, is it possible to have a multipart request sent as one of the requests in a batch?

Yes, you can set custom headers like how you usually set them in single or batch requests. Here’s an example for both of your questions:

import http from "k6/http";

export default function () {
    let payload = {
        someFile: http.file("some file data, maybe via open()", "test.txt"),
        someNonFileData: "whatever",
    };
    let params = {
        headers: {
            "my-special-header": "foo",
        },
        timeout: 2000,
    };

    let postResponse = http.post("https://httpbin.test.loadimpact.com/post", payload, params);
    console.log(postResponse.body);
    let batchResponses = http.batch([
        ["POST", "https://httpbin.test.loadimpact.com/post", payload, params],
        ["POST", "https://httpbin.test.loadimpact.com/post", payload, { headers: { "some-other-header": "bar" } }],
        ["GET", "https://httpbin.test.loadimpact.com/anything", null, params],
    ]);
    console.log(batchResponses[1].body);
}

This would output something like this:

{
  "args": {}, 
  "data": "", 
  "files": {
    "someFile": "some file data, maybe via open()"
  }, 
  "form": {
    "someNonFileData": "whatever"
  }, 
  "headers": {
    "Content-Length": "408", 
    "Content-Type": "multipart/form-data; boundary=551edbbd317cbea6471a55ab1a71e09b4a674629b90c9e8ec792c477b2d7", 
    "Host": "httpbin.test.loadimpact.com", 
    "My-Special-Header": "foo", 
    "User-Agent": "k6/0.26.0 (https://k6.io/)", 
  }, 
  "json": null, 
  "url": "https://httpbin.test.loadimpact.com/post"
} 
{
  "args": {}, 
  "data": "", 
  "files": {
    "someFile": "some file data, maybe via open()"
  }, 
  "form": {
    "someNonFileData": "whatever"
  }, 
  "headers": {
    "Content-Length": "408", 
    "Content-Type": "multipart/form-data; boundary=f514b810aaeb5969fce380049a85f26cfa89ecd699733d337af6a5dad759", 
    "Host": "httpbin.test.loadimpact.com", 
    "Some-Other-Header": "bar", 
    "User-Agent": "k6/0.26.0 (https://k6.io/)", 
  }, 
  "json": null, 
  "url": "https://httpbin.test.loadimpact.com/post"
} 

1 Like