search
HomeWeb Front-endHTML TutorialHow ueditor rich text editor implements cross-domain upload of images

This article mainly introduces the method and process of uploading images across domains in the ueditor rich text editor. Friends who are interested can learn about it. I hope it will be helpful to you.

In the process of uploading images using Baidu Rich Text Editor, if you have a separate image server, you need to put the uploaded images on the image server, such as uploading images in the editor of a.com, The image needs to be saved to img.com, which involves cross-domain uploading of images, and the official documentation of ueditor says that cross-domain uploading of single images is not supported. I checked all kinds of bells and whistles online, and the operation is as fierce as a tiger, such as adding a document. .domain, configuring the full domain name, etc. are all the same. I dared to define it as cross-domain without knowing what cross-domain is. I carefully studied the demo file of ueditor and came up with a compromise. It is very simple and only requires Just modify the code in two places in the demo and write an upload interface:

First introduce the page ueditor editor. I won’t go into details here. You can refer to a previous article:How to Html Insert Baidu rich text editor ueditor, here by default you have implemented the introduction of ueditor as shown below:

1. At this time, the images you upload are saved locally. If you want to transfer them across domains to other servers, you need to add the image configuration item imageUrlPrefix in the ueditor/php/config.json configuration file. Domain name, so that after you upload the image, what is returned to you is the full path of the image, which can be displayed anywhere. I use the client a.com to upload the image to img.com through the editor, so imageUrlPrefix is configured as http://img.com. Note that it must be the full domain name with http://:

2 After modifying the access path, you also need to modify the ueditor/php/Uploader.class.php file and find the upFile() method. This method is the main processing method for uploading files in the demo. What is better than modifying this upload method? It is simpler and easier to understand the proxy page and adding js. Even if it is imported into multiple pages, there will be no problem:

  private function upFile()
    {
        $file = $this->file = $_FILES[$this->fileField];
        if (!$file) {
            $this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
            return;
        }
        if ($this->file['error']) {
            $this->stateInfo = $this->getStateInfo($file['error']);
            return;
        } else if (!file_exists($file['tmp_name'])) {
            $this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE_NOT_FOUND");
            return;
        } else if (!is_uploaded_file($file['tmp_name'])) {
            $this->stateInfo = $this->getStateInfo("ERROR_TMPFILE");
            return;
        }

        $this->oriName = $file['name'];
        $this->fileSize = $file['size'];
        $this->fileType = $this->getFileExt();
        $this->fullName = $this->getFullName();
        $this->filePath = $this->getFilePath();
        $this->fileName = $this->getFileName();
        $dirname = dirname($this->filePath);

        //检查文件大小是否超出限制
        if (!$this->checkSize()) {
            $this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
            return;
        }

        //检查是否不允许的文件格式
        if (!$this->checkType()) {
            $this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
            return;
        }

        //创建目录失败
        if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
            $this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
            return;
        } else if (!is_writeable($dirname)) {
            $this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
            return;
        }

        //移动文件
        if (!(move_uploaded_file($file["tmp_name"], $this->filePath) && file_exists($this->filePath))) { //移动失败
            $this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
        } else { //移动成功
            $this->stateInfo = $this->stateMap[0];
        }
     /**
      *此处上面的代码都是demo内的源代码不需要改,下面才是我加上的需要敲黑板划重点的地方,说一下思路,上面的代码会在本地生成上传的图片内容,然后我们就可以拿到上传的文件的全路径,
      *拿到全路径再调用事先封装好的上传接口上传到图片服务器即可,由于第一步配置了图片服务器的域名,所以最后返回给编辑器窗口的图片路径已经是带域名的全路径啦
      */
     $imgPath = '@'.$dirname.'/'.$this->fileName;//获取生成的本地文件完整路径
      
     //发送请求的参数
     $data = [
            'myFile'=>$imgPath,
            'imgType'=>4
        ];
     $serverUrl = 'http://img.com/api/image.action'; //请求地址
        $ch = curl_init(); //初始化
        curl_setopt($ch, CURLOPT_URL, $serverUrl);   
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        //https协议需要以下两行,否则请求不成功
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        //post方法所需要的参数
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array());
        $result = curl_exec($ch);
        curl_close($ch);

        $result = json_decode($result,true); //将接口返回的json数据转为数组
        $this->fullName = $result['imgUrlNormal']; //重置要返回给编辑器窗口的图片路径,这一步可以让图片在编辑器内正常显示图片
    }

3. After changing these two places, write it yourself An interface for uploading images. Cache the above request address to your interface address. It is relatively simple and there are a lot of examples. I will not post them here. In this way, in three steps, you can upload images across domains without any accident. No matter what It can be a single picture or multiple pictures, it is simple, easy to understand and convenient! ! !

Related tutorials: HTML video tutorial

The above is the detailed content of How ueditor rich text editor implements cross-domain upload of images. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
Why are HTML tags important for web development?Why are HTML tags important for web development?May 02, 2025 am 12:03 AM

HTMLtagsareessentialforwebdevelopmentastheystructureandenhancewebpages.1)Theydefinelayout,semantics,andinteractivity.2)SemantictagsimproveaccessibilityandSEO.3)Properuseoftagscanoptimizeperformanceandensurecross-browsercompatibility.

Explain the importance of using consistent coding style for HTML tags and attributes.Explain the importance of using consistent coding style for HTML tags and attributes.May 01, 2025 am 12:01 AM

A consistent HTML encoding style is important because it improves the readability, maintainability and efficiency of the code. 1) Use lowercase tags and attributes, 2) Keep consistent indentation, 3) Select and stick to single or double quotes, 4) Avoid mixing different styles in projects, 5) Use automation tools such as Prettier or ESLint to ensure consistency in styles.

How to implement multi-project carousel in Bootstrap 4?How to implement multi-project carousel in Bootstrap 4?Apr 30, 2025 pm 03:24 PM

Solution to implement multi-project carousel in Bootstrap4 Implementing multi-project carousel in Bootstrap4 is not an easy task. Although Bootstrap...

How does deepseek official website achieve the effect of penetrating mouse scroll event?How does deepseek official website achieve the effect of penetrating mouse scroll event?Apr 30, 2025 pm 03:21 PM

How to achieve the effect of mouse scrolling event penetration? When we browse the web, we often encounter some special interaction designs. For example, on deepseek official website, �...

How to modify the playback control style of HTML videoHow to modify the playback control style of HTML videoApr 30, 2025 pm 03:18 PM

The default playback control style of HTML video cannot be modified directly through CSS. 1. Create custom controls using JavaScript. 2. Beautify these controls through CSS. 3. Consider compatibility, user experience and performance, using libraries such as Video.js or Plyr can simplify the process.

What problems will be caused by using native select on your phone?What problems will be caused by using native select on your phone?Apr 30, 2025 pm 03:15 PM

Potential problems with using native select on mobile phones When developing mobile applications, we often encounter the need for selecting boxes. Normally, developers...

What are the disadvantages of using native select on your phone?What are the disadvantages of using native select on your phone?Apr 30, 2025 pm 03:12 PM

What are the disadvantages of using native select on your phone? When developing applications on mobile devices, it is very important to choose the right UI components. Many developers...

How to optimize collision handling of third-person roaming in a room using Three.js and Octree?How to optimize collision handling of third-person roaming in a room using Three.js and Octree?Apr 30, 2025 pm 03:09 PM

Use Three.js and Octree to optimize collision handling of third-person roaming in the room. Use Octree in Three.js to implement third-person roaming in the room and add collisions...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.