do_upload_paste.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. window.addEventListener('DOMContentLoaded', function() {
  2. if(window.location.pathname.match(/^\/edit\//i)) {
  3. const textarea = document.querySelector("textarea");
  4. if (textarea) {
  5. textarea.addEventListener("paste", pasteListener);
  6. }
  7. }
  8. });
  9. function pasteListener(e) {
  10. // find file
  11. if (e.clipboardData && e.clipboardData.items) {
  12. const items = e.clipboardData.items;
  13. let haveImageInClipboard = false;
  14. const formData = new FormData();
  15. for (let i = 0; i < items.length; i++) {
  16. if (items[i].type.indexOf("image") !== -1) {
  17. const file = items[i].getAsFile();
  18. const customName = prompt("파일 이름을 설정해주세요. (확장자는 생략)");
  19. if (!customName) {
  20. return alert("취소되었습니다.");
  21. }
  22. const customFile = new File([file], customName + ".png", { type: file.type });
  23. formData.append("f_data[]", customFile);
  24. haveImageInClipboard = true;
  25. e.preventDefault();
  26. break;
  27. }
  28. }
  29. if (!haveImageInClipboard) {
  30. return;
  31. }
  32. // send to server
  33. fetch("/upload", {
  34. method: "POST",
  35. body: formData,
  36. }).then((res) => {
  37. if (res.status === 200 || res.status === 201) {
  38. const url = res.url;
  39. alert(
  40. '클립보드의 이미지를 성공적으로 업로드했습니다. 아래 텍스트로 본문에 삽입할 수 있습니다.' +
  41. '[[' + decodeURIComponent(url.replace(/.*\/w\/file/, "file")) + ']]'
  42. );
  43. } else {
  44. console.error("[ERROR] PasteUpload Fail :", res.statusText);
  45. alert("클립보드의 이미지를 업로드하는데 실패했습니다. 파일 이름 중복일 수 있습니다.");
  46. }
  47. }).catch((err) => {
  48. console.error("[ERROR] PasteUpload Fail :", JSON.stringify(err), err);
  49. alert("클립보드의 이미지를 업로드하는데 실패했습니다. 파일 이름 중복일 수 있습니다.");
  50. });
  51. }
  52. }