upload_image_with_paste.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. const customFile = new File([file], customName + ".png", { type: file.type });
  25. formData.append("f_data[]", customFile);
  26. haveImageInClipboard = true;
  27. e.preventDefault();
  28. break;
  29. }
  30. }
  31. if (!haveImageInClipboard) return;
  32. // send to server
  33. fetch("/upload", {
  34. method: "POST",
  35. body: formData,
  36. })
  37. .then((res) => {
  38. if (res.status === 200 || res.status === 201) {
  39. const url = res.url;
  40. alert(
  41. `이미지 복붙 업로드 성공. 다음 텍스트로 본문에 삽입할 수 있습니다 : [[${url.replace(
  42. /.*\/w\/file/,
  43. "file"
  44. )}]]`
  45. );
  46. } else {
  47. console.error("[ERROR] PasteUpload Fail :", res.statusText);
  48. alert("이미지 복붙 업로드에 실패했습니다. 파일명 중복일 수 있습니다.");
  49. }
  50. })
  51. .catch((err) => {
  52. console.error("[ERROR] PasteUpload Fail :", JSON.stringify(err), err);
  53. alert("이미지 복붙 업로드에 실패했습니다. 파일명 중복일 수 있습니다.");
  54. });
  55. }
  56. }