Search code examples
javascriptformsfiledojo

Is it possible to replace a file input with a Blob?


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?


Solution

  • 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.