5

Is there currently no support for submitting multipart form data with a request?

I understand how to perform a POST with d3.json().post() as described here, but I wanted to use POST to submit parameters to an API via multipart/form-data.

It seems strange that I can not find any resources on how best to do this; the closest I have come is https://github.com/mbostock/d3/issues/929 and https://github.com/mbostock/d3/wiki/Requests but these do not really cover multipart forms.

Is there an undocumented part of the functionality described in #929 that I couldn't find in d3.v3.js which would allow for use of multipart forms? Is anyone currently working on or interested in this issue?

Community
  • 1
  • 1
hushedfeet
  • 51
  • 4
  • While I have created a suitable workaround for this issue, it would still be nice if it was supported. If anyone else has trouble with this and would like to work on committing a solution, please let me know. – hushedfeet Dec 15 '12 at 00:01
  • 1
    You should post your workaround as an answer. While you might not want to mark it as accepted (since it sounds like you still want a better solution), it would help others who need something. – Joshua Taylor Apr 21 '15 at 17:52

1 Answers1

3

There are three steps to a successful multipart post.

  1. Add the header Content-type: application/x-www-form-urlencoded
  2. Encode the form data
  3. Concatenate it as if you were specifying query strings in a URL

Then just send it as the POST data.

None of this is specific to d3, but I thought I'd give my answer and some sample code, since I landed here.

Sample code:

var xhr = d3.xhr(post_url)
    .header("Content-type", "application/x-www-form-urlencoded");

xhr.post("arg1=" + encodeURIComponent(arg1) + "&arg2=" + encodeURIComponent(arg2),
  function(error, result) {
    if(error)
        throw new Error(error);
    read_paths.data(JSON.parse(result.responseText));
});
Gordon
  • 18,882
  • 4
  • 33
  • 72