Home > Enterprise >  Drop or Paste file on the Textarea
Drop or Paste file on the Textarea

Time:04-29

I want to make a message input like this. enter image description here

But I have a question how to get file data, which I drag & drop or Ctrl V on the textarea to upload. I am using Riot.js and Symfony for this.

Here is my uncompleted code:

<form method="post" enctype="multipart/form-data" onsubmit="{ handleFileSubmit }">
   <textarea  id="message" onpaste="{ handleFilePaste }" required> 
   </textarea>
</form>

handleFilePaste(e) {
  e.preventDefault();
  console.log(e.clipboardData.items);
  console.log(window.navigator.clipboard);
}

But the above console.log() didn't get any file data when I copy a file on my local drive and paste it on the textarea. If someone knows how to do it or have a good sample link, please share with me.

If you can, please share the drag & drop sample(important: the input field must be textarea).

I hope good replies. Thank you.

CodePudding user response:

When I had to do something similar in the past I didn't attach the eventlistener to the form itself, but to document as shown in the example below (which you can execute and paste something, it works), technically I'm not sure if it works the same on a textarea but it does work on document, it's not that important where you listen for the paste event as you are then deciding what you do when you detect a file being pasted.

function handleFilePaste(e) {

  const items = (e.clipboardData || e.originalEvent.clipboardData).items;
  console.log(items);
  
  for (let index in items) {
    const item = items[index];
    if (item.kind === 'file') {
      return item.getAsFile();
    }
  }
}

document.addEventListener('DOMContentLoaded', () => {
  document.onpaste = function(e){
    const file = handleFilePaste(e);
    console.log(file);
    
    if ( !file ) { return; }
  }
});
<form method="post" enctype="multipart/form-data" onsubmit="{ handleFileSubmit }">
   <textarea  id="message" placeholder="Paste something" required> 
   </textarea>
</form>

  • Related