iT邦幫忙

0

Django | 如何使用富文本編輯器將圖片上傳資料庫

如題,想請問有人有研究Django富文本編輯器嗎? 用ckeditor,文章的圖片好像只能放到指定路徑下。

請問有人有推薦的富文本編輯器嗎,而且希望可以將圖片上傳到mysql資料庫中

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
froce
iT邦大師 1 級 ‧ 2020-02-27 22:37:01
最佳解答

使用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沒啥問題,問題是你不會做後端的圖片處理...

我要發表回答

立即登入回答