tinymce圖片上傳


一、概述

對於上傳圖片功能,tinymce提供了很多相關配置http://tinymce.ax-z.cn/configure/file-image-upload.php

這里我們對其中的自定義上傳圖片進行簡單的講解,需要用到images_upload_url屬性。

 

二、更改配置

在上一篇文章中,鏈接如下:https://www.cnblogs.com/xiao987334176/p/14596776.html

已經實現了tinymce的安裝和使用,打開頁面,點擊圖片上傳。

彈出框

 注意:默認只能插入一個瀏覽器能訪問到圖片地址。

 

如果我需要上傳本地文件,怎么辦呢?修改初始化配置

以上一篇文章中的tinymce_demo項目為例,修改文件src/components/Tinymce/index.vue

增加images_upload_url屬性

...
window.tinymce.init({
    images_upload_url: 'http://127.0.0.1:8000/file/excel_upload/',
    language: this.language,
...

注意:images_upload_url就是指后端api圖片上傳地址。

 

關於這個api接口,我采用的是django項目開發的,參考鏈接:https://www.cnblogs.com/xiao987334176/p/14361854.html

注意:需要修改一下視圖函數才能使用。

修改api/views.py,完整內容如下:

from rest_framework.views import APIView
from upload_demo import settings
from django.shortcuts import render, redirect, HttpResponse
from django.http import JsonResponse
from rest_framework import status
import os
import uuid


class File(APIView):
    def post(self, request):
        print(request.FILES)
        # 接收文件
        file_obj = request.FILES.get('file', None)
        print("file_obj", file_obj.name)

        # 判斷是否存在文件夾
        head_path = os.path.join(settings.BASE_DIR,'static')
        print("head_path", head_path)
        # 如果沒有就創建文件路徑
        if not os.path.exists(head_path):
            os.makedirs(head_path)

        # 判斷文件大小不能超過5M
        if file_obj.size > 5242880:
            return JsonResponse({'status': status.HTTP_403_FORBIDDEN, 'msg': '文件過大'},
                                status=status.HTTP_403_FORBIDDEN)

        # 文件后綴
        suffix = file_obj.name.split(".").pop()
        print("文件后綴", suffix)  # 圖片后綴 png

        # 判斷文件后綴
        # suffix_list = ["xlsx","xls"]
        # if suffix not in suffix_list:
        #     return JsonResponse({'status': status.HTTP_403_FORBIDDEN, 'msg': '只能選擇excel文件'},
        #                         status=status.HTTP_403_FORBIDDEN)

        # 重命名文件名
        file_name = '%s.%s'%(uuid.uuid4(),suffix)
        print("file_name",file_name)
        # 儲存路徑
        file_path = os.path.join(head_path,file_name)
        print("儲存路徑", file_path)

        # 寫入文件到指定路徑
        with open(file_path, 'wb') as f:
            for chunk in file_obj.chunks():
                f.write(chunk)

        data = {}
        data['status'] = status.HTTP_200_OK
        data['name'] = file_name
        data['location'] = "http://127.0.0.1:8000/static/{}".format(file_name)
        return JsonResponse(data, status=status.HTTP_200_OK)
View Code

注意:api返回的json中,必須包含location字段,比如:{ "location": "folder/sub-folder/new-location.png" }

 

我返回的api信息如下:

{'status': 200, 'name': '448c0db3-4162-4330-9981-eae1960606eb.jpg', 'location': 'http://127.0.0.1:8000/static/039f4e72-097e-4a2c-b0dc-2539f78eb325.jpg'}

多幾個字段無所謂,只要有location就行。

 

三、上傳文件

再次點擊圖片上傳,會發現多了一個上傳選項

選擇一張圖片,注意:上傳成功后,會顯示圖片像素大小。如下圖:

點擊確定,效果如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM