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?
To construct a Blob from other non-blob objects and data, use the Blob() constructor. To create a blob that contains a subset of another blob's data, use the slice() method. To obtain a Blob object for a file on the user's file system, see the File documentation.
A Blob is an opaque reference to, or handle for, a chunk of data. The name comes from SQL databases, where it means “Binary Large Object.” In JavaScript, Blobs often represent binary data, and they can be large, but neither is required: a Blob could also represent the contents of a small text file.
A Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.
In HTML, we will use the type attribute to take input in a form and when we have to take the file as an input, the file value of the type attribute allows us to define an element for the file uploads.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With