Skip to content

Instantly share code, notes, and snippets.

@stuartnelson3
Created July 31, 2014 18:24
Show Gist options
  • Save stuartnelson3/f29c631db652f907f0d9 to your computer and use it in GitHub Desktop.
Save stuartnelson3/f29c631db652f907f0d9 to your computer and use it in GitHub Desktop.
Upload file on textarea drop
function addImageMarkdown(e, altText, imagePath) {
var startPos = e.selectionStart;
var endPos = e.selectionEnd;
e.value = e.value.substring(0, startPos)
+ "![" + altText + "](" + imagePath + ")"
+ e.value.substring(endPos, e.value.length);
}
$(document).on('drop', 'textarea', function(e) {
e.preventDefault();
var dt = e.originalEvent.dataTransfer;
var f = dt.files[0];
t = e.currentTarget;
// Adds markdown for image to textarea at cursor position.
addImageMarkdown(t, f.name, " ... ");
var fd = new FormData();
fd.append("file", f);
var request = new XMLHttpRequest();
request.open("POST", "/upload");
request.onloadend = function(e) {
// The response is the path to the file on the server.
var resp = e.currentTarget.response;
// Update the text with the correct path for the image.
t.value = t.value.replace(/\.\.\./, resp.slice(1));
$(t).keyup();
};
request.send(fd);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment