使用quill,這個範例是從前端ajax傳image到後端,在記憶體中轉換成base64,再傳回前端。
自己去改自己需要的。
template
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.quilljs.com/1.3.6/quill.snow.css" rel="stylesheet">
<title>Document</title>
</head>
<body>
<div id="editor">
<p>Hello World!</p>
<p>Some initial <strong>bold</strong> text</p>
<p><br></p>
</div>
{% csrf_token %}
</body>
</html>
<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
<script>
var quill = new Quill('#editor', {
modules: {
toolbar: [
[{ header: [1, 2, false] }],
['bold', 'italic', 'underline'],
['image', 'code-block']
]
},
placeholder: 'Compose an epic...',
theme: 'snow' // or 'bubble'
});
function selectLocalImage() {
const input = document.createElement('input');
input.setAttribute('type', 'file');
input.click();
input.onchange = () => {
const file = input.files[0];
if (/^image\//.test(file.type)) {
saveToServer(file);
} else {
console.warn('You could only upload images.');
}
};
}
function saveToServer(file) {
const fd = new FormData();
fd.append('image', file);
fd.append('csrfmiddlewaretoken', document.querySelector("[name=csrfmiddlewaretoken]").value);
const xhr = new XMLHttpRequest();
xhr.open('POST', '/upload/image/', true);
xhr.onload = () => {
if (xhr.status === 200) {
const res = JSON.parse(xhr.responseText);
insertToEditor(res);
}
};
xhr.send(fd);
}
function insertToEditor(res) {
const range = quill.getSelection();
quill.insertEmbed(range.index, 'image', `data:${res.type};base64,${res.data}`);
}
quill.getModule("toolbar").addHandler("image", selectLocalImage)
</script>
views.py
from django.http import JsonResponse
from io import BytesIO
from base64 import b64encode
from django.shortcuts import render
def quill(request):
return render(request, "quilltest.html")
def uploadFile(request):
image = request.FILES.get("image", None)
if image:
imageB64 = b64encode(BytesIO(image.read()).getvalue()).decode("utf-8")
else:
imageB64 = None
# 自己把imageB64存進去...
res = {
'name': image.name,
'type': image.content_type,
'data': imageB64
}
return JsonResponse(res)
urls.py
path('', quill),
path('upload/image/', uploadFile),
然後瞄了一眼ckeditor...
應該前端送到server沒啥問題,問題是你不會做後端的圖片處理...