1.0.4 • Published 1 year ago

html-base64-img-to-upload v1.0.4

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

if a html string contain IMG tags which url is base64 ,is to large to post api,before we do that, we can find the base64 IMG tags.and replace their url with the uploaded url.

一种常用的场景:

在大多数情况下,在我们前端的 富文本提交时候,如果 html 字符串中的 tag img,如果没有特殊处理的,图片有可能是 base64 形式的 ,相当于把整个图片文件大小 放入了 html 片段中,这样在表单提交的时候,文件会很大,而且在数据回显访问的时候,接口响应会很 慢我们需要的解决方法,是把 base64 图片在表单提交之前 替换为 上传到云服务上之后的图片 url,

  • 一种解决方法是对我们的富文本编辑器做处理,使其配置为 base64 图片上传到服务器,获取到 url,再替换到富文本 im 标签上。但 是这种富文本编辑器的插件 可能不是很完美,有的地方转换可能会有出入,图片,文本复制有偏差。
  • 另一种解决方法是,我们再提交表单的时候,对富文本中的 html 片段识别处理,将其中的 base64 图片上传之后替换为绝对 url,然 后再提交,这个就是我们当前这个插件实现的功能,省去了大家重复的劳动力

usage:

  import { matchBase64ThenUpload } from 'html-base64-img-to-upload';

  ...

  /**
   * editorStr: html String
   * uploadApi: return uploaded pic url, data structor: {code,messge,data}  res.data
   * limitNum: if base64 string length less than this,nothing todo,else upload; default:0
   */
  matchBase64ThenUpload(editorStr, uploadApi,limitNum).then(handledHtmlStr=>{
    // do something
  })  

  /**
   * about uploadApi code preview,so your uploadApi is a post api,a promise. its received params is {file:file}
   * the pic uploadUrl is res.data, adapt your function to it
   * */
   return new Promise((resolve, reject) => {
        var data = { file: baseFile };
        uploadApi(data)
          .then(
            (res) => {
              resolve({
                id: i,
                res,
                imgTag:`<img src="${res.data}" >`,
                imgUrl: res.data,
              });
            },
            (err) => {
              resolve({
                id: i,
                res: err,
                imgTag:`<img src="${err.data}" >`,
                imgUrl: err.data,
              });
              reject(err);
            }
          )
          .catch((er) => {
            reject(er);
          });
      });