javascript cannot be manipulated...">

Entering an Html file, setting a selection from a File object

I understand that by default for <input type="file"> javascript cannot be manipulated for security reasons, but is it possible if I have a File object?

I have a drag area on the page from which I can get a File object. I do not want to use xhr.sendAsBinary, I would rather just load from a regular form with the target set as a frame.

I tried to do something like

 var select = document.getElementById('upload_1'); select.files[0] = myFile; myForm.submit(); 

Is there any way to do this?

+6
source share
1 answer

UPDATE

It looks like you want to take the File object from the drop event and assign it to the <input> element. Unfortunately, you cannot do this. Only the user can select files; you cannot dynamically change the files that will be downloaded, because browsers refuse this feature for security reasons.


Since you said you have a drag area, I assume that you are using and setting up a browser that supports drag and drop. Please note that not all browsers support drag and drop, so my example here is limited to such browsers.

When you drag and drop, you can get the File object from the drag event, and you do not need the input element.

 // when you attach the 'drop' event listener var dropzone = document.getElementById('drag_area'); // <-- ID of your drag area attachEvent(dropzone, 'drop', function(event) { var dt = event.dataTransfer; var fileList = dt.files; var file = fileList[0]; // you would have to change this if you allow multi-file upload uploadFile(file); }); function uploadFile(fileToUpload) { var xhr = new XMLHttpRequest(); xhr.open("POST", "url", true); // <-- provide the proper URL var form_data = new FormData(); form_data.append('file', fileToUpload); xhr.send(form_data); } function attachEvent(element, type, fn) { if (element.addEventListener) { element.addEventListener(type, fn, false); } else if (element.attachEvent) { element.attachEvent('on' + type, fn); } } 

Please note that this is not 100% compatible with the browser. Some browsers do not support downloading files via XMLHttpRequest() . If you want to support these browsers, you need to do something else.

Finally, my example does not address the use of forms. If you want to use a form based form, please let me know. I can also help you with this :)

Let me know if you have any questions.

+5
source

Source: https://habr.com/ru/post/903567/


All Articles