yzernik
yzernik

Reputation: 1191

How do I dynamically add a file input to FormData in Dart?

I am trying to use the FormData class to send data to my server with HttpRequest.send(). I need to do a POST request with multiple fields. It should work the same as this Javascript code:

//Upload File
var uploadFile = function(file, tag, callback)
{
    var xhr = new XMLHttpRequest();
    xhr.open('POST', "upload/", true);
    xhr.onreadystatechange=function()
    {
        if (xhr.readyState==4 && xhr.status==200)
        {
            callback();
        }
    }
    var formData = new FormData();
    formData.append('file', file);
    formData.append('tag', tag);
    var csrftoken = $.cookie('csrftoken');
    xhr.setRequestHeader("X-CSRFToken", csrftoken);
    xhr.send(formData);
};

But FormData doesn't seem to work the same way in Dart. Could someone explain how to do this in Dart, if it is possible?

Upvotes: 5

Views: 2889

Answers (2)

Alexandre Ardhuin
Alexandre Ardhuin

Reputation: 76193

You have to use FormData.appendBlob :

void uploadFile(File file, String tag, callback) {
  final xhr = new HttpRequest();
  xhr.open('POST', "upload/", true);
  xhr.on.readyStateChange.add((e) {
    if (xhr.readyState == 4 && xhr.status == 200) {
      callback();
    }
  });
  final formData = new FormData();
  formData.appendBlob('file', file);
  formData.append('tag', tag);
  xhr.send(formData);
};

Upvotes: 2

Seth Ladd
Seth Ladd

Reputation: 120529

Unfortunately this looks to be a bug. I've opened issue http://code.google.com/p/dart/issues/detail?id=7152 to track. Thanks for the use case.

Upvotes: 3

Related Questions