【问题标题】:TinyMCE Image Uploader with Specified Upload Path具有指定上传路径的 TinyMCE 图像上传器
【发布时间】:2021-10-20 18:58:48
【问题描述】:

我想知道有什么方法可以使用 TinyMCE 中的本地文件选择器上传图片,我们可以指定图片上传路径?以前我已经制作了一个本地文件(图像)选择器,但是当我上传它时,图像将作为 base64 编码图像存储在 txt 文件中。我想要的是将图像直接保存到我的服务器,并将“img src”作为指定的上传路径。有人知道执行此操作的代码吗?感谢所有帮助,非常感谢!

28/8/2021 我想根据@Dmitry D 建议的答案更新我当前的代码。我已经将 automatic_uploads 设置为“true”,并指定了习惯于我的本地目录的上传目录,但它仍然返回 405 http 错误。

目前我正在使用 TinyMCE 5.8.2 生产包 我已经设置了 FLASK_ENV = development 和 FLASK_APP = app

这是我的 index.html

<body>
    <div class="container">
        <div class="row">
            <h2>TinyMCE Upload Image with Python Flask</h2>
            <form id="posts" name="posts" method="post" action="./static/tinymce/postAcceptor.php">
                <textarea name="message" id="message"></textarea><br>
            </form>
        </div>
    </div>
<script src="./static/tinymce/tinymce.min.js"></script>
<script>
    tinymce.init({
        selector: "textarea#message",
        plugins: "code image",
        toolbar: 'undo redo image',
        image_title: true,
        automatic_uploads: true,
        images_upload_url: './static/tinymce/postAcceptor.php',
        images_upload_credentials: true,
        file_picker_types: 'image',
    });
</body>

app.py(Flask 框架)

from flask import Flask, render_template, jsonify, request
from werkzeug.utils import secure_filename
import os
import urllib.request
 
app = Flask(__name__)

@app.route('/')
def main():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)

postAcceptor.php

<?php
  /***************************************************
   * Only these origins are allowed to upload images *
   ***************************************************/
  $accepted_origins = array("http://localhost", "http://127.0.0.1");

  /*********************************************
   * Change this line to set the upload folder *
   *********************************************/
  $imageFolder = "./static/uploads/";

  if (isset($_SERVER['HTTP_ORIGIN'])) {
    // same-origin requests won't set an origin. If the origin is set, it must be valid.
    if (in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)) {
      header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
    } else {
      header("HTTP/1.1 403 Origin Denied");
      return;
    }
  }

  // Don't attempt to process the upload on an OPTIONS request
  if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    header("Access-Control-Allow-Methods: POST, OPTIONS");
    return;
  }

  reset ($_FILES);
  $temp = current($_FILES);
  if (is_uploaded_file($temp['tmp_name'])){
    /*
      If your script needs to receive cookies, set images_upload_credentials : true in
      the configuration and enable the following two headers.
    */
    // header('Access-Control-Allow-Credentials: true');
    // header('P3P: CP="There is no P3P policy."');

    // Sanitize input
    if (preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $temp['name'])) {
        header("HTTP/1.1 400 Invalid file name.");
        return;
    }

    // Verify extension
    if (!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "png"))) {
        header("HTTP/1.1 400 Invalid extension.");
        return;
    }

    // Accept upload if there was no origin, or if it is an accepted origin
    $filetowrite = $imageFolder . $temp['name'];
    move_uploaded_file($temp['tmp_name'], $filetowrite);

    // Determine the base URL
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? "https://" : "http://";
    $baseurl = $protocol . $_SERVER["HTTP_HOST"] . rtrim(dirname($_SERVER['REQUEST_URI']), "/") . "/";

    // Respond to the successful upload with JSON.
    // Use a location key to specify the path to the saved image resource.
    // { location : '/your/uploaded/image/file'}
    echo json_encode(array('location' => $baseurl . $filetowrite));
  } else {
    // Notify editor that the upload failed
    header("HTTP/1.1 500 Server Error");
  }
?>

我的目录大致是这样的:

图片上传/ -app.py
-venv
-静态
----上传
----小小
--------tinymce.min.js
--------postAcceptor.php
-模板
----index.html

在我编写flask run,然后单击图像按钮后,上传菜单就在那里,我可以从本地目录浏览,但是当我尝试上传它时,它显示“HTTP:错误405”。我试图检查它,并在控制台菜单上发现了一个错误,上面写着“POST http://localhost:5000/static/tinymce/postAcceptor.php 405 (METHOD NOT ALLOWED)”

有人知道这是怎么发生的以及如何解决吗?非常感谢你们!

【问题讨论】:

    标签: javascript html jquery css tinymce


    【解决方案1】:

    automatic_uploads 选项应该会有所帮助。它将自动在服务器上上传图像,并将 blob URL 替换为文件的真实路径。下面是 PHP upload handler 的示例,它将上传图片并将其 URL 返回给 TinyMCE。

    【讨论】:

    • 那么我应该将 automatic_uploads 设置为 True 吗? tinymce 脚本上还有其他设置/配置吗? link --> 目前我正在使用本网站中提到的 javascript,但它返回的是 base64 编码的图像。我需要实现的 tinymce 脚本有什么变化吗?谢谢!
    • 是的,您需要将 'automatic_uploads' 设置为 'true' 并在您的服务器上处理这些上传。例如,通过使用上述示例 PHP 脚本。如果您使用基本文件选择器而不设置上传,TinyMCE 仍会将 base64 blob 放在页面上。
    • 感谢您的帮助,我还有一些问题。如何将 php 脚本设置为处理文件选择器的脚本?如果我使用 python 的烧瓶而不是 php 来处理它,是否有可能?谢谢!
    • 请仔细查看文档。答案在 autmatic_uploads 示例中是正确的:images_upload_url: 'postAcceptor.php',
    • 我目前正在使用 python 的烧瓶作为 web 框架,如果我使用 PHP 作为 postAcceptor(服务器端处理程序)会导致错误吗?我在上面的问题中添加了我的代码。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-10
    • 2020-05-31
    • 2015-02-05
    • 2012-06-07
    • 1970-01-01
    • 2011-06-16
    相关资源
    最近更新 更多