11

I am working with an online application of which I do not have access to the source, but I am able to inject javascript on it via iframe because I can create pages in the same domain.

This application has a form it submits for file upload, and file inputs, think:

<form>
   <!-- lots and lots of inputs -->
   <input type="file" name="blah">
</form>

I would like to use this form to submit a javascript Blob for this particular file instead of a file from disk, while not disturbing the rest of the form. How do I do this?

3
  • 1
    You can use XHR2(ajax) to do this, specifically with FormData.
    – Musa
    Commented Feb 19, 2014 at 21:35
  • use a hidden input w/ base64 file data, custom handling on the server required.
    – dandavis
    Commented Feb 19, 2014 at 21:52
  • That sounds like the kind of solution I was hoping for, but I don't have access to server-side code. I'm stuck with a terrible content management system. Commented Feb 19, 2014 at 23:11

2 Answers 2

17

It is possible to replace file input value with blob.

To do this you have to construct File object from it like this:

let file = new File([blob], "filename.ext",{type:"mime/type", lastModified:new Date().getTime()});

Then create DataTransfer object and add this file to it.

 let container = new DataTransfer();
 container.items.add(file);

This will populate file list of DataTransfer, which can be assigned to file property of file input.

fileInputElement.files = container.files;

As can be seen in fiddle, it is correctly assigned. Also, I tested the upload (with input in form with enctype="multipart/form-data") and the file is passed to server correctly.

0
3

It's possible with the new properties of XMLHttpRequest and FormData

Thanks to @musa for his comment ;-)

Consider this (untested) example:

function sendFile() {
  var content = "<hello>world</hello>"; // set here the content of your file
  var blob = new Blob([content], { type: "text/xml"}); // set the type of content (eg: image/jpeg)

  var formData = new FormData();
  formData.append('blah', blob);

  var xhr = new XMLHttpRequest();
  xhr.open('POST', '/server', true);
  xhr.onload = function(e) {
    alert ('successfully (or not) sent');
  };

  xhr.send(formData);
}

More informations:

Notice: FormData is not supported by IE9 (and less)

This is the same for Blob

1
  • I've tried using FormData and emulating the POST data that the large unreadable blob of Dojo code on the page I'm modifying sends to the server, but no avail. I was hoping to simply modify the html element on the page and let the Dojo code take over and do its thing. If this were a personal project were I have everything organized and under my control this would be a great solution. Commented Feb 19, 2014 at 23:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.