ChatGPT work efficiency improvement layedit upload multiple attachment solutions (layedit assignment, layui.js underlying modification, append mode multi-attachment upload)

ChatGPT Work Efficiency Improvement Series Article Catalog

  1. A Preliminary Exploration of the Way of ChatGPT Work Efficiency Improvement
  2. Ingenuity and instructions in program development for improving ChatGPT work efficiency (creating MySQL statements, PHP statements, Javascript usage, python interaction)
  3. ChatGPT work efficiency to generate development requirements and quotations and convert them to Excel format
  4. ChatGPT Work Efficiency Improvement Goose Pass Secondary Development Batch API Docking Solution (Learning Record Synchronization, User Registration Synchronization, Rights Order Synchronization, Development Documentation)
  5. ChatGPT work efficiency improvement using python to develop a practical plan for docking Baidu Maps Open Platform API (batch route planning, batch POI acquisition, breakthrough number limit, batch geocoding)

insert image description here

foreword


Layui has a component called layedit. Although the layedit component has been deprecated as early as the Layui 2.0 version released in 2017 , it has not been officially removed from the built-in components of Layui in order to take care of a small number of groups who still insist on using the layedit component. remove.

In the previous project, there was such an embarrassing situation. If you want to replace it with a new one, it is not allowed in terms of time and cost. However, the needs of customers have increased the demand for uploading attachments, and they have to be satisfied. When using ChatGPT to improve work efficiency, complete customer needs, and by the way, write out the gap between ChatGPT and reality in the actual development work, for mutual encouragement.

1. ChatGPT-oriented programming: clear requirements

Q1: What is the solution for uploading attachments in layedit?

1. Feedback from ChatGPT

Layedit is a rich text editor based on the layui framework, which supports uploading images and attachments. When uploading attachments, you can use code written in PHP or other back-end languages ​​to receive uploaded files.

HTML code:

<div class="layui-form-item">
    <label class="layui-form-label">附件上传</label>
    <div class="layui-input-block">
        <!-- layedit上传插件 -->
        <textarea id="content" name="content"></textarea>
    </div>
</div>

JavaScript code:

layui.use(['layedit', 'upload'], function(){
    
    
  var layedit = layui.layedit
  ,upload = layui.upload;
  
  // 构建编辑器
  var index = layedit.build('content');

  // 监听上传按钮点击事件
  upload.render({
    
    
    elem: '#test2'
    ,url: '/upload/' //后台上传接口
    ,accept: 'file'
    ,done: function(res){
    
    
      layedit.insertFile(index, {
    
    
        url: res.data.src,
        title: res.data.title
      });
    }
  });
});

In this example layedit, uploada rich text editor with attachment upload is built by importing and modules. When the upload button is clicked, the attachment is uploaded to /upload/the interface , and the file address and file name after the upload is successful are inserted into the editor.

Code example of background PHP receiving files:

if ($_FILES['file']['error']) {
    
    
  // 上传失败
} else {
    
    
  $fileName = $_FILES['file']['name'];
  $fileTempName = $_FILES['file']['tmp_name'];

  // 文件上传成功,将文件移动到指定目录并重命名
  move_uploaded_file($fileTempName, 'path/to/upload/' . $fileName);

  // 返回上传成功结果
  $result = array(
    'code' => 0,
    'msg' => '',
    'data' => array(
      'title' => $fileName,
      'src' => 'path/to/upload/' . $fileName
    )
  );
  echo json_encode($result);
}

In this example, the uploaded file is moved to the specified directory and renamed through the PHP move_uploaded_file()function , and then a successful upload result is returned, including the file name and path of the attachment. This result will be processed in a callback function in the front-end JavaScript, inserting it into the editor. It should be noted that this is just a basic example, and it needs to be modified and expanded according to specific needs in actual use. At the same time, it is also necessary to pay attention to security, restrict and verify the type and size of uploaded files, and prevent files containing malicious code from being uploaded.

2. Feedback Verification of ChatGPT

  • There is no layedit.insertFile function in layedit, and other HTML and backend tests are normal.
 ,done: function(res){
    
    
      layedit.insertFile(index, {
    
    
        url: res.data.src,
        title: res.data.title
      });

layui has no insertFile function, how to solve it?

Indeed, Layui's layeditmodule does not have insertFilea function. This is probably because insertFilethe function is provided in some custom extension.

If you need to insert the uploaded file in Layui's rich text editor, you can use layedit.insert()the method . This method can insert elements such as text, pictures, and videos into the editor, but you need to handle the HTML code of the elements yourself.

The following is an example of processing the returned data after a successful upload and inserting a file link into the editor:

layui.use(['layedit', 'upload'], function () {
    
    
  var layedit = layui.layedit;
  var upload = layui.upload;
  var index = layedit.build('content');

  // 绑定上传按钮
  upload.render({
    
    
    elem: '#uploadBtn',
    url: '/file/upload/api',
    done: function (res) {
    
    
      if (res.success) {
    
    
        // 插入文件链接
        var link = '<a href="' + res.url + '">' + res.fileName + '</a>';
        layedit.insert(index, link);
      } else {
    
    
        layer.msg(res.message, {
    
     icon: 5 });
      }
    },
    error: function () {
    
    
      layer.msg('上传失败', {
    
     icon: 5 });
    }
  });
});

In this example, upload.render()the method . After the upload is successful, insert the returned file link into the editor. Of course, you can also extend layeditthe module , adding insertFilefunctions or other functions you need. For details, refer to Layui's official documentation: Extension Module - Extend Custom Extension .

Consider insertFilethe development cost issue, stop this question and continue with the following questions:

  • HTML has no upload button?

Q2. Where is the button to upload attachments? Does it need to be developed separately?

When uploading an attachment using the Layedit editor, the upload button is not in the editor and is not displayed by default. A component with an upload button needs to be developed or configured separately to trigger file upload events. Here are some common scenarios:

1. Use uploadthe component to manually trigger the upload event.
For example, add an upload button in HTML, and use JavaScript to bind the content of the editor to the upload button, and trigger the upload event in the button click event:

<div class="layui-input-block">
    <!-- 文本编辑器 -->
    <textarea id="content" name="content"></textarea>
    <!-- 上传按钮 -->
    <button type="button" class="layui-btn" id="uploadBtn">上传附件</button>
</div>
layui.use(['layedit', 'upload'], function () {
    
    
  var layedit = layui.layedit;
  var upload = layui.upload;
  var index = layedit.build('content');

  // 点击上传按钮
  $('#uploadBtn').on('click', function () {
    
    
    // 进行上传
    upload.render({
    
    
      elem: this,
      url: 'upload.php',
      accept: 'file',
      done: function (res) {
    
    
        if (res.code == 0) {
    
    
          // 上传成功,插入到编辑器中
          layedit.insertFile(index, {
    
    
            url: res.data.src,
            title: res.data.title
          });
        } else {
    
    
          // 上传失败
          layer.msg('上传失败');
        }
      },
      error: function () {
    
    
        // 请求异常
        layer.msg('上传异常');
      }
    });
  });
});

In this example, upload.render()the method to bind the upload event to the upload button. The upload event is triggered when the upload button is clicked, and the attachment is inserted into the editor after the upload is successful.

1. BUG in the solution

$('#uploadBtn').on('click', function () {},The layui upload button itself triggers the open file box. Using this method is redundant and affects normal operation.

2. Add an upload button to the editor's toolbar.

Use Layui's custom toolbar example to add an upload button to the editor's toolbar and trigger the upload event through JavaScript.

HTML code:

<div class="layui-form-item">
  <label class="layui-form-label">正文内容</label>
  <div class="layui-input-block">
    <div id="edit" class="layui-layedit">
      <!-- 在工具栏中添加了 “上传” 操作按钮 -->
      <textarea id="content" name="content"></textarea>
    </div>
  </div>
</div>

JavaScript code:

layui.use(['layedit', 'upload'], function () {
    
    
  var layedit = layui.layedit;
  var upload = layui.upload;
  var content = layedit.build('content', {
    
    
    tool: [
      'strong', // 加粗
      'italic', // 斜体
      'underline', // 下划线
      'del', // 删除线
      '|', // 分割线
      'left', // 左对齐
      'center', // 居中对齐
      'right', // 右对齐
      '|', // 分割线
      'link', // 超链接
      'face', // 表情
      'image', // 插入图片
      '|', // 分割线
      {
    
     // 自定义上传按钮
        title: '上传',
        icon: 'layui-icon-upload-drag',
        event: function () {
    
    
          // 触发上传事件
          upload.render({
    
    
            elem: this,
            url: 'upload.php',
            accept: 'file',
            done: function (res) {
    
    
              if (res.code == 0) {
    
    
                // 上传成功,插入到编辑器中
                layedit.insertFile(index, {
    
    
                  url: res.data.src,
                  title: res.data.title
                });
              } else {
    
    
                // 上传失败
                layer.msg('上传失败');
              }
            },
            error: function () {
    
    
              // 请求异常
              layer.msg('上传异常');
            }
          });
        }
      }
    ]
  });
});

In this example, an editor is initialized using layedit.build()the method and an "upload" action button is added. The upload event is triggered when the upload button is clicked, and the uploaded attachment is inserted into the editor after successful upload.

2. Method Validation

can not achieve.

{
    
     // 自定义上传按钮
        title: '上传',
        icon: 'layui-icon-upload-drag',
        event: function () {
    
    
          // 触发上传事件
          upload.render({
    
    
            elem: this,
            url: 'upload.php',
            accept: 'file',
            done: function (res) {
    
    
              if (res.code == 0) {
    
    
                // 上传成功,插入到编辑器中
                layedit.insertFile(index, {
    
    
                  url: res.data.src,
                  title: res.data.title
                });
              } else {
    
    
                // 上传失败
                layer.msg('上传失败');
              }
            },
            error: function () {
    
    
              // 请求异常
              layer.msg('上传异常');
            }
          });

The upload button added in the editor's toolbar cannot be displayed normally. What's the problem?

When adding a toolbar button in the Layedit editor, if the icon of the button cannot be displayed normally, it may be because the corresponding icon file cannot be found or the icon used is incorrect. Here are some solutions for your reference:

  1. Check icon file path

When adding a button, you need to use the icon in the icon library that comes with Layui, and the name usually layui-icon-starts with . If the icon does not display properly, it may be because the icon file path is wrong. When using it, it is recommended to use layui's official CDN to avoid path errors:

<link rel="stylesheet" href="https://www.layuicdn.com/layui/css/layui.css">
<script src="https://www.layuicdn.com/layui/layui.js"></script>
  1. Check icon name

When adding a button, you need to use the correct icon name. If the name is incorrect, Layui will not recognize the style and display it as the default icon. You can determine the icon name by looking at Layui's icon collection.

  1. custom icon

If you need to use a custom icon, you can put the icon file in the same directory as layui.css, and add the icon style in the style sheet:

.icon-upload {
    
    
  background-image: url('./upload.png') !important;
}

When adding a button, you can use a custom class name as the icon, for example:

'custom-upload': {
    
    
  title: '上传',
  layEvent: 'custom-upload',
  icon: 'icon-upload'
}

Hope the above information is helpful to you.

Two, CSDN-oriented programming: core development

Since ChatGPT provides ideas for solving problems, proceed in a quick and effective way:

  • Added upload attachment button;
  • After uploading the file, the parameter will be returned and assigned to the rich text box of layui;
  • Append mode, support multi-attachment upload

1. layedit is assigned to layedit.setContent

The layedit.setContent method is not specified in the official documentation of layui, and everything depends on searching.

/**
* 设置编辑器内容
* @param {[type]} index 编辑器索引
* @param {[type]} content 要设置的内容
* @param {[type]} flag 是否追加模式
*/
layedit.setContent(index, content, flag);
flag是true,是追加模式,
flag是false,赋值模式

2. Layedit.setContent assignment reports an error

  • ReferenceError: layedit is not defined
    insert image description here

3. Layui.js underlying modification (2.68)

insert image description here

//把layui.js 里查找 layedit.sync(t)
layedit.sync(t)
//改为
this.sync(t)
//即可解决这个问题

Summarize

In the development process for ChatGPT, it provides some practical functions to help programmers improve efficiency in development, but experienced and basic programmers are required to verify and practice.

  • Code debugging: ChatGPT can help programmers to debug code, and automatically generate corresponding code suggestions and problem solutions according to the input code segments and problem prompts.
  • Coding Standards: ChatGPT can help programmers follow coding standards and provide code style and standard recommendations.
  • Technical knowledge consultation: ChatGPT can answer questions related to technical knowledge, including technical fields such as programming languages, algorithms, data structures, operating systems, and networks.

In the actual development process, modify and expand according to specific needs. Overall, ChatGPT can provide programmers with some practical functions to help improve efficiency and quality in development.


@leak time sometimes

Supongo que te gusta

Origin blog.csdn.net/weixin_41290949/article/details/130912312
Recomendado
Clasificación