PHP建站技术分享-从入门到精通PHP建站技术分享-从入门到精通PHP建站技术分享-从入门到精通

QQ:420220301 微信/手机:150-3210-7690
当前位置:首页 > CMS教程 > Fastadmin

解决富文本编辑器 Nkeditor 下载远程图片时跨域问题

管理员 2024-12-14
Fastadmin
7

由于某些情况会重写 addon.js, 该文章只具有参考处理思路作用,切勿直接使用

产生情况:
点击Nkeditor插件的 下载远程图片 按钮可能会产生

问题描述:
Access to image at 'xxx' from origin 'xxx' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

仅做临时处理方案,许多情况未考虑。 php > 5.6 、composer

解决方案:

当图片加载出现问题时由服务器去进行图片下载, 具体如下

引入 composer

composer require greeflas/php-image-downloader:dev-master

修改 PHP 文件

  1. application/admin/controller/Ajax.php
    新增方法 imageDownloadByUrl
    image.png
public function imageDownloadByUrl(){    $url = $this->request->request('url');    $extparam = $this->request->post();    if (empty($url)) {        $this->error(__('No file upload or server upload limit exceeded'));    }    $upload = Config::get('upload');    $info = explode('/',$url);    $fileInfo = [];    $fileInfo['name'] = end($info);    $fileInfo['tmp_name'] = $url;    $name_arr = explode('.', $fileInfo['name']);    $fileInfo['type'] = end($name_arr);    $sha1 = md5($url);    $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));    $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';    $replaceArr = [        '{year}'     => date("Y"),        '{mon}'      => date("m"),        '{day}'      => date("d"),        '{hour}'     => date("H"),        '{min}'      => date("i"),        '{sec}'      => date("s"),        '{random}'   => Random::alnum(16),        '{random32}' => Random::alnum(32),        '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],        '{suffix}'   => $suffix,        '{.suffix}'  => $suffix ? '.' . $suffix : '',        '{filemd5}'  => md5_file($fileInfo['tmp_name']),    ];    $savekey = $upload['savekey'];    $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);    $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);    $fileName = substr($savekey, strripos($savekey, '/') + 1);    $downloader = new greeflastoolsImageDownloader([        'class' => greeflastoolsvalidatorsImageValidator::class    ]);    $splInfo = $downloader->download($url, ROOT_PATH . '/public' . $uploadDir, $fileName);    if ($splInfo) {        $params = array(            'admin_id'    => (int)$this->auth->id,            'user_id'     => 0,            // 'filesize'    => $fileInfo['size'],            // 'imagewidth'  => $imagewidth,            // 'imageheight' => $imageheight,            'imagetype'   => $suffix,            'imageframes' => 0,            'mimetype'    => $fileInfo['type'],            'url'         => $uploadDir . $fileName,            'uploadtime'  => time(),            'storage'     => 'local',            'sha1'        => $sha1,            'extparam'    => json_encode($extparam),        );        $attachment = model("attachment");        $attachment->data(array_filter($params));        $attachment->save();        thinkHook::listen("upload_after", $attachment);        $this->success(__('Upload successful'), null, [            'url' => $params['url']        ]);    } else {        // 上传失败获取错误信息        $this->error('上传失败');    }}

修改 js 文件

  1. public/assets/js/addons.js
    image.png
 img.onerror = function () {    Fast.api.ajax({        url: 'ajax/imageDownloadByUrl',        data: {url: url},    }, function (data) {        console.log(data)        if (data.url) img.src = data.url    });}

希望以上内容对你有所帮助!如果还有其他问题,请随时提问。 各类知识收集 拥有多年CMS企业建站经验,对 iCMS, Fastadmin, ClassCMS, LeCMS, PbootCMS, PHPCMS, 易优CMS, YzmCMS, 讯睿CMS, 极致CMS, Wordpress, HkCMS, YznCMS, WellCMS, ThinkCMF, 等各类cms的相互转化,程序开发,网站制作,bug修复,程序杀毒,插件定制都可以提供最佳解决方案。

相关推荐

扫码关注

qrcode

QQ交谈

回顶部