Web Development. Client Satisfaction. Web Consultancy. Professional. UX. Fast. Responsive Design. Dynamic. Interactive. Innovative. Ecommerce. Wordpress plugins. Prestashop modules. You name it.

How To Paste Image On Textarea With jQuery

How To Paste Image On Textarea With jQuery

In this tutorial I will show you how you can upload by ajax an image after you paste it on textarea using jquery. Is very useful this feature because you don't lost any time when it comes to send files to other person. Especially when you do a printscreen using windows tool, you just copy paste the image, and it will be saved to the server. In order to implement this functionality we will need the following html.

<form class="form_paste_image">
  <textarea placeholder="Send a message"></textarea>

The next step is to attach an event listener when this textarea, when paste event is triggered we will know to check the data which was added to the textarea. If the content of the textarea is type of image we will know what to do with it.

jQuery paste event

So using the following js we will be able to detect what type of content the textarea has and send it to the server in order to be saved.

jQuery('.form_paste_image textarea').on('paste', function(e){
  var data = e.originalEvent;
  if (data.clipboardData && data.clipboardData.items) {
      var items = data.clipboardData.items;
      for (var i = 0; i < items.length; i++) {
        if (items[i].type.indexOf('image') !== -1) {
          var file = items[i].getAsFile(),
          	  data = new FormData(),
      	  data.append('file[]', file);

The above code will do all the work in order to work this functionality. As you can see in the ajax code I used contentType, processData and cache parameters, these are required in order to be able to upload the image to the server using ajax. The above code will work only if the page is not loaded by ajax, if you load the textarea using ajax you will have to attach the paste event on the body then point to the textarea. Let me know if this function worked for you, if not maybe I can help you with your issues, just hit the comments section for this.

Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x