7

I'm aware of the security reasons that local file cannot be set as a file programmatically to input field. Suppose I've this image as base64:

var bus = "data:image/gif;base64,R0lGODlhPQBEAPeoAJosM//AwO/AwHVYZ/z595kzAP/s7P+goOXMv8+fhw/v739/f+8PD98fH/8mJl+fn/9ZWb8/PzWlwv///6wWGbImAPgTEMImIN9gUFCEm/gDALULDN8PAD6atYdCTX9gUNKlj8wZAKUsAOzZz+UMAOsJAP/Z2ccMDA8PD/95eX5NWvsJCOVNQPtfX/8zM8+QePLl38MGBr8JCP+zs9myn/8GBqwpAP/GxgwJCPny78lzYLgjAJ8vAP9fX/+MjMUcAN8zM/9wcM8ZGcATEL+QePdZWf/29uc/P9cmJu9MTDImIN+/r7+/vz8/P8VNQGNugV8AAF9fX8swMNgTAFlDOICAgPNSUnNWSMQ5MBAQEJE3QPIGAM9AQMqGcG9vb6MhJsEdGM8vLx8fH98AANIWAMuQeL8fABkTEPPQ0OM5OSYdGFl5jo+Pj/+pqcsTE78wMFNGQLYmID4dGPvd3UBAQJmTkP+8vH9QUK+vr8ZWSHpzcJMmILdwcLOGcHRQUHxwcK9PT9DQ0O/v70w5MLypoG8wKOuwsP/g4P/Q0IcwKEswKMl8aJ9fX2xjdOtGRs/Pz+Dg4GImIP8gIH0sKEAwKKmTiKZ8aB/f39Wsl+LFt8dgUE9PT5x5aHBwcP+AgP+WltdgYMyZfyywz78AAAAAAAD///8AAP9mZv///wAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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MbabI/iBCliMLEJKX2EEkomBAUCxRi42VDADxyTYDVogV+wSChqmKxEKCDAYFDFj4OmwbY7bDGdBhtrnTQYOigeChUmc1K3QTnAUfEgGFgAWt88hKA6aCRIXhxnQ1yg3BCayK44EWdkUQcBByEQChFXfCB776aQsG0BIlQgQgE8qO26X1h8cEUep8ngRBnOy74E9QgRgEAC8SvOfQkh7FDBDmS43PmGoIiKUUEGkMEC/PJHgxw0xH74yx/3XnaYRJgMB8obxQW6kL9QYEJ0FIFgByfIL7/IQAlvQwEpnAC7DtLNJCKUoO/w45c44GwCXiAFB/OXAATQryUxdN4LfFiwgjCNYg+kYMIEFkCKDs6PKAIJouyGWMS1FSKJOMRB/BoIxYJIUXFUxNwoIkEKPAgCBZSQHQ1A2EWDfDEUVLyADj5AChSIQW6gu10bE/JG2VnCZGfo4R4d0sdQoBAHhPjhIB94v/wRoRKQWGRHgrhGSQJxCS+0pCZbEhAAOw==";

I want to set it to an input type file programmatically. Please do not suggest to send this as a string to server because I cannot control the API at the other end.

I tried to convert it to blob in my code and set it to input field as:

myInputField.value = blob;

but it throws security exception:

Uncaught DOMException: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.

Is it possible via javascript? I, by no means, want to involve the file chooser dialog box.

Thank you.

mehulmpt
  • 15,861
  • 12
  • 48
  • 88
  • 1
    `Is it possible via javascript?` - well, the error states `which may only be programmatically set to the empty string` - so, the conclusion is ... – Jaromanda X Mar 14 '17 at 04:36

3 Answers3

6

Not possible. An HTML file input can only point to a file that actually exists on the computer -- it can't point to an arbitrary chunk of data.

  • That's not entirely true, IIRC, on windows, you have/had the ability to enter an URL in the file upload popup's field, I can't test right now if you can pass dataURI too, but anyway. – Kaiido Mar 14 '17 at 05:06
  • So I tested it through a VM, and it only accepts URL, not dataURI, but still it's not necessarily on user's machine. – Kaiido Mar 14 '17 at 05:22
  • 1
    Hijacking accepted answer since this is where Google led me first, it's possible now: https://stackoverflow.com/questions/47119426/how-to-set-file-objects-and-length-property-at-filelist-object-where-the-files-a/47172409#47172409 – Luke Vo Aug 16 '20 at 19:59
2

No you can't set the value of a file input*, except to clear it, but it sounds that it's not what you need anyway.
Instead, convert this dataURI to a Blob, then append this Blob to a FormData and finally post this FormData.

Your image will be sent as multipart like you seem to need.

function dataURItoBlob(data) {
  var binStr = atob(data).split(',')[1],
   len = binStr.length,
   arr = new Uint8Array(len);

  for (var i = 0; i < len; i++) {
    arr[i] = binStr.charCodeAt(i);
  }
  return new Blob(arr);
}

var dataURI = 'data:image/....';
var blob = dataURItoBlob(dataURI);

// you can even pass a <form> in this constructor to add other fields
var formData = new FormData(); 
formData.append('yourFileField', blob, 'fileName.ext');

var xhr = new XMLHttpRequest();
xhr.open('post', yourServer);
xhr.send(formData);

// now you can retrieve your image as a File/multipart with the 'yourFileField' post name

*Actually now you can do it, but it's still rather hackish.

scunliffe
  • 62,582
  • 25
  • 126
  • 161
Kaiido
  • 123,334
  • 13
  • 219
  • 285
  • I'm working on an API, rather. I just have to change the value of the input type file and the listeners will fire up. Moreover, the communication of file is going over a secured websocket whose variable reference is not available to me. So this isn't gonna help. – mehulmpt Mar 14 '17 at 05:47
  • @MehulMohan **You can't**. Modify your API so that it accepts you pass directly a Blob, instead of reading a file input's `files` property, or ultimately, you could probably pass an object like `{files:[blob]}` instead of the file input, since I guess your API is only reading for it. (It may also want some name property, so in this case, just add it to the resulting Blob object, or create a `new File(blob, name)`, but for websocket, you can just do `socket.send(blob)`. – Kaiido Mar 14 '17 at 05:51
1

You can try like below one. Convert your sting to Blob and create file type with created Blob.

var debug = {hello: "world"};
var blob = new Blob([JSON.stringify(debug, null, 2)], {type : 'application/json'});

var outputfile=new File([blob], "filename")
  • That won't change the fact that you cannot set an file input's value. Also, a File object is just a Blob with a `name` and a `lastModified` property. All you can do with a File can be done with a Blob. – Kaiido Mar 14 '17 at 05:32