Reputation: 2037
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?
Upvotes: 11
Views: 10892
Reputation: 1005
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.
Upvotes: 17
Reputation: 4882
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
Upvotes: 3