| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- // editor.js - 编辑器增强
- document.addEventListener('DOMContentLoaded', function () {
- const uploadBtn = document.getElementById('uploadImageBtn');
- const fileInput = document.getElementById('imageFileInput');
- const markdownTextarea = document.getElementById('markdownContent');
- const statusDiv = document.getElementById('uploadStatus');
- if (!uploadBtn || !fileInput || !markdownTextarea) return;
- // 点击按钮触发文件选择
- uploadBtn.addEventListener('click', function () {
- fileInput.click();
- });
- fileInput.addEventListener('change', function () {
- const file = fileInput.files[0];
- if (!file) return;
- // 显示上传中
- statusDiv.textContent = '上传中...';
- uploadBtn.disabled = true;
- const formData = new FormData();
- formData.append('image', file);
- fetch('/editor/upload-image', {
- method: 'POST',
- body: formData
- })
- .then(response => response.json())
- .then(data => {
- if (data.success) {
- // 插入 Markdown 到光标位置
- const start = markdownTextarea.selectionStart;
- const end = markdownTextarea.selectionEnd;
- const before = markdownTextarea.value.substring(0, start);
- const after = markdownTextarea.value.substring(end);
- markdownTextarea.value = before + data.markdown + '\n' + after;
- // 移动光标到插入之后
- markdownTextarea.selectionStart = markdownTextarea.selectionEnd = start + data.markdown.length + 1;
- markdownTextarea.focus();
- statusDiv.textContent = '图片已插入';
- } else {
- statusDiv.textContent = '上传失败: ' + (data.error || '未知错误');
- }
- })
- .catch(err => {
- statusDiv.textContent = '上传错误: ' + err.message;
- })
- .finally(() => {
- uploadBtn.disabled = false;
- fileInput.value = ''; // 以便再次选择同一文件
- });
- });
- });
|