Javascript dataTransfer and input type = file problem

As part of the part of the work I need to do, I am trying to add a javascript drag and drop function. Usually when you drop by drop, you pass event.dataTransfer.files to ajax call to an external file (e.g. upload.php) to save the file. However, in my case, I need to integrate it with an existing form that has a <input type="file"> field.

Is there a way to get event.dataTransfer.files information when you delete a file in the "drop zone" and enter it in the <input type="file"> field so that when the form is event.dataTransfer.files , the file is loaded (for example, imitated click "view" in the field file and select file)?

+4
source share
1 answer

Yes, the input [type = file] is read-only for security reasons. I just solved a similar problem by converting the input [type = file] to the input [type = hidden] and setting the value as base64 encoded URI.

(By the way, this automatically works with Paperclip https://github.com/thoughtbot/paperclip/blob/master/lib/paperclip/io_adapters/data_uri_adapter.rb )

Here is my jquery code:

 $(function() { function renderPreviewImageFromFile(e,file) { file = file || $(this).prop('files')[0]; if(file) { var img = $(this).parents('li').find('img.preview'); var reader = new FileReader(); reader.onload = function(e) { img.attr('src', e.target.result); } reader.readAsDataURL(file); return img.attr('src'); } } $("ul.images-list") .on('change','input.file',renderPreviewImageFromFile); jQuery.event.props.push("dataTransfer"); $('.file-drop') .on('dragover dragenter', function(e) { $(this).addClass('hover'); e.preventDefault(); e.stopPropagation(); }).on('dragleave dragexit', function(e) { $(this).removeClass('hover'); e.preventDefault(); e.stopPropagation(); }).on('drop', function(e) { $(this).removeClass('hover').find('span').remove(); e.preventDefault(); e.stopPropagation(); // change input into hidden field file = e.dataTransfer.files[0]; input = $(this).parents('li').find('input.file'); value = renderPreviewImageFromFile.apply(input, [null, file]); input.attr('type','hidden').val( value ).parents('div.input').hide(); }); }); 
0
source

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


All Articles