美文网首页quill
ngx-quill富文本框使用+图片上传

ngx-quill富文本框使用+图片上传

作者: 李逸101 | 来源:发表于2018-08-22 22:20 被阅读0次

    在网上找了很多angular的富文本框组件,体验最好的是Froala这一款,但是要收费.后面又找到了这ngx-quill.搜了下quill的使用方法但是很少说到图片上传.所以自己研究了一下.现在把它分享出来.

    1. 安装ngx-quill
    npm install --save ngx-quill
    

    2.在index.html引入css

    <link href="https://cdn.quilljs.com/1.2.2/quill.snow.css" rel="stylesheet">
    

    3.在模块中引入

    import { QuillModule } from 'ngx-quill';
    
    @NgModule({
      imports: [
        ...
        QuillModule
        ...
      ],
    })
    export class xxxModule { }
    

    4.在对应的html中引入

           <quill-editor 
             (onEditorCreated)="EditorCreated($event)" 
             [(ngModel)]='textDetail'>
           </quill-editor>
    

    5.在component中实现图片上传的处理器

    public editor;
    
    EditorCreated(quill) {
        const toolbar = quill.getModule('toolbar');
        toolbar.addHandler('image', this.imageHandler.bind(this));
        this.editor = quill;
      }
    
    imageHandler() {
        const Imageinput = document.createElement('input');
        Imageinput.setAttribute('type', 'file');
        Imageinput.setAttribute('accept','image/png, image/gif, image/jpeg, image/bmp, image/x-icon');
        Imageinput.classList.add('ql-image');
        Imageinput.addEventListener('change', () => {
          const file = Imageinput.files[0];
          const data: FormData = new FormData();
          data.append('file', file, file.name);
          const header = new Headers();
          header.append('Accept', 'application/json');
          const options = new RequestOptions({ headers: header });
          if (Imageinput.files != null && Imageinput.files[0] != null) {
            this.http.post('http://xxxx/upload', data, options)
            .map(res => res.json())
            .subscribe(res => {
              const range = this.editor.getSelection(true);
              const index = range.index + range.length;
              this.editor.insertEmbed(range.index, 'image', 'http://'+res.url);
            });
          }
        });
        Imageinput.click();
      }
    

    7.效果图


    image.png

    8.后台上传接口

    @RequestMapping(value = "/upload", method = {RequestMethod.POST})
        @ResponseBody
        public FileUploadResponse upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
            String remotePath = nginxServer + "/";
            // 判断文件夹是否存在,不存在则
            File targetFile = new File(basePath);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            FileUploadResponse rs = new FileUploadResponse();
            String contentType = file.getContentType();
            String fileName = file.getOriginalFilename();
            String fileNameSuffix = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            String fileNameNew = uuid + fileNameSuffix;
            try {
                Files.copy(file.getInputStream(), Paths.get(basePath, fileNameNew), StandardCopyOption.REPLACE_EXISTING);
                rs.setContentType(contentType);
                rs.setFileName(fileNameNew);
                rs.setUrl(remotePath + fileNameNew);
                rs.setType("success");
                log.info(JSON.toJSONString(rs));
            } catch (Exception e) {
                rs.setType("fail");
                rs.setMsg("文件上传失败!");
                log.error("上传文件失败," + e);
            }
            return rs;
        }
    

    9.富文本框内容需要转码(保存时转码,查看时解码)

    /*用正则表达式实现html转码*/
      htmlEncodeByRegExp(str) {
        var s = "";
        if (str.length == 0) return "";
        s = str.replace(/&/g, "&amp;");
        s = s.replace(/</g, "&lt;");
        s = s.replace(/>/g, "&gt;");
        s = s.replace(/\'/g, "&#39;");
        s = s.replace(/\"/g, "&quot;");
        s = s.replace(/\n"/g, "");
        s = s.replace(/\r"/g, "");
        return s;
      }
      /*用正则表达式实现html解码*/
      htmlDecodeByRegExp(str) {
        var s = "";
        if (str.length == 0) return "";
        s = str.replace(/&amp;/g, "&");
        s = s.replace(/&lt;/g, "<");
        s = s.replace(/&gt;/g, ">");
        s = s.replace(/&nbsp;/g, " ");
        s = s.replace(/&#39;/g, "\'");
        s = s.replace(/&quot;/g, "\"");
        return s;
      }
    

    10.参考的资料
    upload images to the server and render it using image url
    file-upload-in-angular

    相关文章

      网友评论

        本文标题:ngx-quill富文本框使用+图片上传

        本文链接:https://www.haomeiwen.com/subject/mnruiftx.html