upload_image_with_paste.js 2.2 KB

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