Uploading Content-Type: multipart/form-data

462 views
Skip to first unread message

alec

unread,
May 29, 2013, 9:16:44 PM5/29/13
to closure-lib...@googlegroups.com
I need to upload an image file along with some POST variables using multipart/form-data Content-Type.

With native JavaScript API I would do something like:

var fd = new FormData();
fd.append("fileField", myFile);
var xhr = new XMLHttpRequest();
xhr.open("POST", "file_handler.php");
xhr.send(fd);


goog.net.XhrIo() does not seem to support this? Is this possible with Closure Library at all? 

Nathan Wright

unread,
May 30, 2013, 1:41:59 PM5/30/13
to closure-lib...@googlegroups.com
goog.net.XhrIo has FormData support as of August 2012 [1], are you by chance using an old version of Closure Library?

Something like this should work (in theory, haven't tested):

var fd = new FormData();
fd.append("fileField", myFile);
var xhr = new goog.net.XhrIo();
xhr.send("file_handler.php", "POST", fd);


Cheers,
Nathan Wright
--
 
---
You received this message because you are subscribed to the Google Groups "Closure Library Discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to closure-library-d...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Message has been deleted
Message has been deleted

alec

unread,
May 30, 2013, 3:38:28 PM5/30/13
to closure-lib...@googlegroups.com
This code works. I have a conceptual question then. 
I have to mix native JS FormData with goog.net.XhrIo. Also, goog.net.XhrIo does not have an easy way to listen to the "progress" events that are emitted by xhr.upload [1], which is a requirement in my case.
Given these consideration, is the best practice to mix native FormData and goog.net.XhrIo or go all native JS API with FormData and XMLHttpRequest?

Nathan Wright

unread,
May 30, 2013, 4:57:15 PM5/30/13
to closure-lib...@googlegroups.com
It's very possible to listen to xhr.upload events, but you'll have to subclass goog.net.XhrIo to get at the underlying XMLHttpRequest.

There are a number of ways you can do this, but in my case I overrode the createXhr method to attach the event listener. Here's a very rough example of what I mean:

my.net.XhrIo.prototype.createXhr = function() {
  var xhr = my.net.XhrIo.superClass_.createXhr.call(this);
  goog.events.listen(xhr.upload, 'progress', this.dispatchEvent, false, this);
  return xhr;
};

(You'll also want to extend cleanUpXhr_ to remove the event listener.)

This will cause 'progress' closure events to be dispatched from the XhrIo object. You can listen for those events and, inside the listener, lookup event.getBrowserEvent().loaded to see how many bytes have been sent.

Hope that helps!

Nathan Wright
Reply all
Reply to author
Forward
0 new messages