Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 375
yzernik Avatar asked Dec 02 '12 19:12

yzernik


2 Answers

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.

like image 61
Seth Ladd Avatar answered Oct 21 '22 01:10

Seth Ladd


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);
};
like image 45
Alexandre Ardhuin Avatar answered Oct 21 '22 01:10

Alexandre Ardhuin