Paste screenshot into a textarea using Paste.js, but how would you transmit it to Rails?

1.6k Views Asked by At

I'm working on a solution that allows to paste screenshots directly into a textarea in Rails, which will be parsed as Markdown lateron.

I found the neat Paste.js library which captures the clipboard, detects whether a string or an image is pasted, and then reacts upon images by converting them into a Base64 string which then can be used as an image.

Being as it is, Paste.js offers everything needed to simply paste a simple image tag into the textarea like this:

![Some alt text](data:image/png;base64,iVBORw0KGgoAA...SUVORK5CYII=)

But this will clutter up the whole textarea, Base64 strings can become very, very long. So I'd like only to be inserted a placeholder like so:

![Some alt text](blob:3857c1cf-1a68-4549-bc0d-aa18af25bb82)

And then, in a hidden input field, I'd like to send the Base64 data:

<input type="hidden" name="post[content][screenshots][3857c1cf-1a68-4549-bc0d-aa18af25bb82]" value="data:image/png;base64,iVBORw0KGgoAA...SUVORK5CYII=" />

My question is now: how would you implement this on the server side in Rails? I simply want to save them as regular files under uploads, where I also store uploads from Carrierwave.

I don't want them to be uploaded automatically when pasted, as users can cancel when creating or editing a post, and I don't want the upload space to be cluttered up with images that are not in use.

Also, I don't want the images (once saved) to be removed from the server again, e.g. when removing the reference from the blog post, as the blog posts are versioned (using PaperTrail) and references will always exist in the old versions, so I think it's sensible to also keep the old images.

Do you think this makes sense? Or do I miss something? Are there limitations I don't see (e.g. upload limit of long Base64 strings)?

Maybe are there other libraries doing the same? I know GitHub Issues support this feature, but I couldn't find out how they did it, and they don't allow pasting screenshots in Firefox, either (which is supported by Paste.js).

1

There are 1 best solutions below

0
On

I had this exact requirement for my blog. Thank for the tip for paste.js; I implemented it and wrote a write up.

I used the following approach to implement it.

  • User pastes an image into the textarea
  • Paste.js captures the base64/png data
  • Ajax this payload to the server
  • Server convert to jpeg
  • Save it on the server
  • Return a markdown link to the front end
  • Append the markdown link to the textarea's content

I want to change that last point so it can remember the location of the user's cursor and insert it there, as opposed to appending it to the end.