Hugh's Blog

OpenCart 编辑器上传问题

今天有个 OpenCart 网站出现了一个问题:文章编辑器上传图片失败。本来以为是修改代码过程中引发了 Bug,但是下载官方代码试了下,一样的问题,版本是 1.5.6.4,在论坛也找到有不少人遇到了一样的问题,由于目前是 1.x 的最后一个版本,而如今正式版都已经 3.x 了,所有也不会有修复了,所幸论坛里有人提供了解决方案,做个记录。

首先定位到使用了 CKEditor 编辑器的模板文件,例如:/path/to/admin/view/template/catalog/product_form.tpl/path/to/admin/view/template/catalog/information_form.tpl

// 找到下面几行
filebrowserUploadUrl: 'index.php?route=common/filemanager&token=<?php echo $token; ?>',
filebrowserImageUploadUrl: 'index.php?route=common/filemanager&token=<?php echo $token; ?>',
filebrowserFlashUploadUrl: 'index.php?route=common/filemanager&token=<?php echo $token; ?>'

// 修改为正确的上传地址
filebrowserUploadUrl: 'index.php?route=common/filemanager/upload&token=<?php echo $token; ?>',
filebrowserImageUploadUrl: 'index.php?route=common/filemanager/upload&token=<?php echo $token; ?>',
filebrowserFlashUploadUrl: 'index.php?route=common/filemanager/upload&token=<?php echo $token; ?>'

接下来修改上传图片逻辑,定位到 /path/to/admin/controller/common/filemanager.php

// 找到下面这行
if (isset($this->request->post['directory'])) { //...

// 在上面那行之前插入下面代码,对于编辑器上传做设置
if (isset($this->request->get['CKEditorFuncNum'])) {
    $this->request->post['directory'] = '';
    $this->request->files['image'] = $this->request->files['upload'];
}

// 找到下面一行
$this->response->setOutput(json_encode($json));

// 替换为下面几行,在返回结果之前,针对编辑器单独处理
if (isset($this->request->get['CKEditorFuncNum'])) {
    if (isset($json['success'])) {
        if (isset($this->request->server['HTTPS']) && (($this->request->server['HTTPS'] == 'on') || ($this->request->server['HTTPS'] == '1'))) {
            $baseUrl = HTTPS_SERVER;
        } else {
            $baseUrl = HTTP_SERVER;
        }
        $baseUrl = str_replace('admin/', '', $baseUrl);
        echo "<script type='text/javascript'>window.parent.CKEDITOR.tools.callFunction(" . $this->request->get['CKEditorFuncNum'] . ", '" . $baseUrl . "image/data/" . $filename . "');</script>";
    } else {
        echo "<script type='text/javascript'>window.parent.alert('{$json['error']}');window.parent.CKEDITOR.tools.callFunction(" . $this->request->get['CKEditorFuncNum'] . ", '');</script>";
    }
} else {
    $this->response->setOutput(json_encode($json));
}

参考

Image upload problem in CKEditor