editor.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // editor.js - 编辑器增强
  2. document.addEventListener('DOMContentLoaded', function () {
  3. const uploadBtn = document.getElementById('uploadImageBtn');
  4. const fileInput = document.getElementById('imageFileInput');
  5. const markdownTextarea = document.getElementById('markdownContent');
  6. const statusDiv = document.getElementById('uploadStatus');
  7. if (!uploadBtn || !fileInput || !markdownTextarea) return;
  8. // 点击按钮触发文件选择
  9. uploadBtn.addEventListener('click', function () {
  10. fileInput.click();
  11. });
  12. fileInput.addEventListener('change', function () {
  13. const file = fileInput.files[0];
  14. if (!file) return;
  15. // 显示上传中
  16. statusDiv.textContent = '上传中...';
  17. uploadBtn.disabled = true;
  18. const formData = new FormData();
  19. formData.append('image', file);
  20. fetch('/editor/upload-image', {
  21. method: 'POST',
  22. body: formData
  23. })
  24. .then(response => response.json())
  25. .then(data => {
  26. if (data.success) {
  27. // 插入 Markdown 到光标位置
  28. const start = markdownTextarea.selectionStart;
  29. const end = markdownTextarea.selectionEnd;
  30. const before = markdownTextarea.value.substring(0, start);
  31. const after = markdownTextarea.value.substring(end);
  32. markdownTextarea.value = before + data.markdown + '\n' + after;
  33. // 移动光标到插入之后
  34. markdownTextarea.selectionStart = markdownTextarea.selectionEnd = start + data.markdown.length + 1;
  35. markdownTextarea.focus();
  36. statusDiv.textContent = '图片已插入';
  37. } else {
  38. statusDiv.textContent = '上传失败: ' + (data.error || '未知错误');
  39. }
  40. })
  41. .catch(err => {
  42. statusDiv.textContent = '上传错误: ' + err.message;
  43. })
  44. .finally(() => {
  45. uploadBtn.disabled = false;
  46. fileInput.value = ''; // 以便再次选择同一文件
  47. });
  48. });
  49. });