3

I need a way to add a File object to a file input field.

Note that I do not want to set the value of the file field. (which is a security risk, ... I know that)
I already have the file itself (and all its contents!)

I'm creating the File object like this:

canvas.toBlob(function(blob) {
  var file = new File([blob], 'file.png');
  // and now I want to add MY File to the input here
});

Please don't tell me about how to upload the File, I know about XMLHttpRequest Level 2. I want to upload the File to an external website (potentially using a userscript or something similar).

So, how can I achieve that? Or if it's not possible: why can't I add a File that I actually own (because I created it in the Browser (as a virtual File, which does not even exist in the users filesystem)) to an input field that I own too? (technically the input field could be my own, that does not matter here)

Community
  • 1
  • 1
  • 2
    Possible duplicate of [Html file input, set selection from File object](http://stackoverflow.com/questions/8469479/html-file-input-set-selection-from-file-object) – Mingle Li Aug 11 '16 at 19:56

2 Answers2

4

No, you can't.

Taken from here:

It seems like you want to take the File object from the drop event and assign it to the element. Unfortunately, you can't do that. Only the user can select files; you can't dynamically change the files which will be uploaded because browsers deny JavaScript this ability for security reasons.

Community
  • 1
  • 1
Mingle Li
  • 1,322
  • 1
  • 15
  • 39
0

Yes it is possible:

To load file from blob:


  let fileInputElement = document.getElementById('file_input');
  let container = new DataTransfer();
  // Here load or generate data
    let data = new Blob();
    let file = new File([data], "g"+i+".jpg",{type:"image/jpeg", lastModified:new Date().getTime()});
    container.items.add(file);
  fileInputElement.files = container.files;

To load file from another file input:


  let input1 = document.getElementById('file_input');
  let input2 = document.getElementById('some_other_input')
  let container = new DataTransfer();
   [...input2.files].map(file=>container.items.add(file));
  input1.files = container.files;

https://jsfiddle.net/Kartearis/gmhwnaz6/3/

Meir
  • 516
  • 4
  • 19