I have a form in which I let the user add up to 5 files in a way that I only show one <input type="file">
and if the user do put a file at the <input>
then I update the form adding another input and so on. It works pretty well when I use the file picker and choose a file. But now I’m trying to add an option so the user can just CTRL+V an image clipboard content directly into the <input>
field and then update the form as said before. I also added a loop verifying if the input fields do have content so the user don’t update, like, the 0th input and then a new input emerges for no necessity. And that’s the point that making my code fail as shown below:
<form class="form-post" role="form" method="POST" enctype="multipart/form-data" action="/someroute">
<!-- other inputs... -->
<input class="novo-post-form-item form-post-file-input" name="arquivos[]" type="file" onchange="addNovoInputFile(this, 5)">
</form>
on the page’s JS:
var addNovoInputFile = function(elem, max){
fileInputs = $('.form-post-file-input');
// When this loop is reached from a copypaste event, the content of fileInputs[0].files is empty
// this doesn't happen when I just select a file from filepicker
for(var i=0; i < fileInputs.length; i++)
{
if(fileInputs[i].files.length === 0)
return;
}
// I put this loop so I don't update the form in case, for example, if the user keeps updating a file at the 0th <input>
// but maybe my solution is just changing the logic of this loop
if(fileInputs.length >= max || elem.files.length === 0)
return;
var novoInput = "<div class="form-post-file-input-box">";
novoInput += "<input class="novo-post-form-item form-post-file-input" name="arquivos[]" type="file" onchange="addNovoInputFile(this, " + max + ")">";
novoInput += "</div>"
$(novoInput).appendTo(".form-post #form-post-file-input-div");
};
// New event I just added in order to fill the input with a printscreen content in the clipboard
window.addEventListener('paste', e => {
let inputs = document.getElementsByName('arquivos[]');
let inputToChange = inputs[inputs.length-1];
if(e.clipboardData.files.length > 0){
inputToChange.files = e.clipboardData.files;
addNovoInputFile(inputToChange, 5);
}
});