@CloudMonster

Как установить image upload на редактор контента Froala?

Здравствуйте!
В админку сайта установил редактор контента Froala Editor.
Там есть кнопка загрузить картинку, но проблема в том, что загрузка идет на их сервер, а не в мой. В документации есть статья об установке editor.froala.com/docs/image-upload-php, на я в ней так и не смог разобраться.

Если кто нибудь сталкивался с такой проблемой в этом редакторе, прошу помочь.
  • Вопрос задан
  • 4013 просмотров
Пригласить эксперта
Ответы на вопрос 2
По ссылке imageUploadURL: '/upload.php' должна быть страница, которая перемещает файл $_FILES['file'] в папку "uploads" с именем sha1(microtime()) . "." . $extension; и в ответ даёт ссылку на него в виде JSON следующего вида
{ link: "uploads/ed13a3f3e78deef2fbeb8a2781297f7860efaa9c.jpg" }
Ответ написан
sergej_saveljev
@sergej_saveljev
js, nodejs, react
Мне понадобились все доступные параметры, с удовольствием поделюсь.
imageUploadURL: 'image_upload.php',
imageUploadParams: {
	path: '/images/'
},
imageManagerLoadURL: 'image_load.php',
imageManagerLoadParams: {
	path: '/images/'
},
imageManagerLoadMethod: 'POST',
imageManagerDeleteURL: 'image_delete.php',


image_upload.php:
// Allowed extentions.
$allowedExts = array("gif", "jpeg", "jpg", "png", "blob");

// Get filename.
$temp = explode(".", $_FILES["file"]["name"]);

// Get extension.
$extension = strtolower(end($temp));

// An image check is being done in the editor but it is best to
// check that again on the server side.
// Do not use $_FILES["file"]["type"] as it can be easily forged.
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($finfo, $_FILES["file"]["tmp_name"]);

if ((($mime == "image/gif")
|| ($mime == "image/jpeg")
|| ($mime == "image/pjpeg")
|| ($mime == "image/x-png")
|| ($mime == "image/png"))
&& in_array($extension, $allowedExts)) {

    $path = base_path() . '/public/images/' . $_POST['path'];
    if ( !is_dir($path) ) \File::makeDirectory($path, 0775, true);

    // image
    $img = $_FILES["file"];
    $name = strtolower($img['name']);
    $src = $path . $name;

    $imgM = Image::make($img['tmp_name']);
    if ( isset($_POST['save']) ){
        $imgM = $imgM->fit(200, 200);
        $user->photo = $_POST['path'].$name;
        $user->save();
    }
    $imgM->save($src);

    // Generate response.
    $response = new \StdClass;
    $response->link = $_POST['path'] . $name;
    echo stripslashes(json_encode($response));
    
}


Данный файл выполняет функцию вывода изображений в список окна выбора ранее загруженных.

image_load.php:
// Array of image objects to return.
$response = array();

// Image types.
$image_types = array(
        "image/gif",
        "image/jpeg",
        "image/pjpeg",
        "image/jpeg",
        "image/pjpeg",
        "image/png",
        "image/x-png"
    );

// Filenames in the uploads folder.
$path = $_POST['path'];

$fnames = scandir($path);

// Check if folder exists.
if ($fnames) {
    // Go through all the filenames in the folder.
    foreach ($fnames as $name) {
        // Filename must not be a folder.
        if (!is_dir($name)) {
            // Check if file is an image.
            if (in_array(mime_content_type(getcwd() . '/' . $path . $name), $image_types)) {
                // Build the image.
                $img = new \StdClass;
                $img->url = $_POST['path'] . $name;
                $img->thumb = $_POST['path'] . $name;
                $img->name = $name;

                // Add to the array of image.
                array_push($response, $img);
            }
        }
    }
}

// Folder does not exist, respond with a JSON to throw error.
else {
    $response = new \StdClass;
    $response->error = "Images folder does not exist!";
}

$response = json_encode($response);

// Send response.
echo stripslashes($response);


image_delete.php:
// Get src.
$src = getcwd() . $_POST["src"];

// delete image
unlink($src);


В коде файлов участвуют классы из laravel, но, я думаю, не составит труда найти подобные в интернете и немного изменить соответствующие участки.
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы