How can I emulate a form submission with a javascript File o

So I have a file object created from a drag and drop into an area from desktop. Now things all dandy, until I have to upload it via Ajax to a Django backend. I would like to utilize the nice Django utils such as request.FILES, etc.Right now, I’m messing with some existing code here:xhr.open(“post”, …

via HTML Language Development » Search Results » ajax:

How can I emulate a form submission with a javascript File o

So I have a file object created from a drag and drop into an area from desktop. Now things all dandy, until I have to upload it via Ajax to a Django backend. I would like to utilize the nice Django utils such as request.FILES, etc.
Right now, I’m messing with some existing code here:
xhr.open(“post”, s.post, true);

// Set appropriate headers
xhr.setRequestHeader(“content-type”, “multipart/form-data”);
xhr.setRequestHeader(“x-file-name”, file.fileName);
xhr.setRequestHeader(“x-file-size”, file.fileSize);
xhr.setRequestHeader(“x-file-type”, file.
xhr.send(file);Try as I might, it doesn’t seem to be emulate a form with a file input submission. Is there something that I am missing?
Thanks!
…………………………………..

You need to create a “FormData” object and then append the file to that as a parameter.
var fd = new FormData();
fd.append(“theFile”, yourFileObject);
//
// … set up the xhr …
//
xhr.send(fd);Obviously this only works in HTML5 environments, but if you’re messing with the File stuff that’s probably something you’re dealing with.
…………………………………..

Unfortunately, you cannot upload a file using the XmlHttpRequest object because it is not supported.
There have been hacky workarounds (like using an iFrame) and recently there is a new File api (https://developer.mozilla.org/en/using_files_from_web_applications) for HTML 5 for browsers that support it.
If you search a little more on stackoverflow, you can find examples on how to do the workarounds.

For more info: How can I emulate a form submission with a javascript File o

HTML Language Development » Search Results » ajax

How can I emulate a form submission with a javascript File o

Share this post:

Related Posts

Leave a Comment