百度编辑器上传word文件转为html

 3109

对于很多网络编辑小白来讲,经常会遇到网站富媒体编辑器,比如百度编辑器,wangeditor编辑器等不会使用,但是word用的很溜的情况,这篇教程教大家二次开发百度编辑器上传word文件转为html的方法,希望对大家有所帮助!

首先:后台上传word转html到编辑器中,编辑器是使用的百度编辑器,先在页面合适的位置写个上传框

  1. <button type="button" name="fileword" id="upload-fileword">上传word文件</button>

前端用的LayUI框架,不需要写提示框,图个方便,大家自行选择

  1. <script>
  2. layui.use('upload', function () {
  3.     var upload = layui.upload;
  4.     upload.render({
  5.         elem:'#upload-fileword',
  6.         accept:'file',
  7.         url: '".url('upload/uploadword',['file'=>'file'])."',
  8.         exts: 'docx',
  9.         done: function(data){
  10.             if(data.status == 1){
  11.                 UE.getEditor('".$field."').setContent(data.html);
  12.                 layer.msg(data.msg,{icon:1,time:1500,shade: 0.1,});
  13.             }else{
  14.                 layer.msg(data.msg,{icon:2,time:1500,shade: 0.1,});
  15.             }
  16.         }
  17.     });
  18. });
  19. </script>

php上传代码

  1. $upload = new \tool\WordUpload(input('file'));
  2. $html = $upload->getHtml();
  3. if ($html === false) {
  4.     return json(['status' => 2, 'html' => $html, 'msg' => '解析失败']);
  5. }else{
  6.     return json(['status' => 1, 'html' => $html, 'msg' => '解析成功']);
  7. }

WordUpload文件 需要phpword包 自己下载

  1. <?php
  2. namespace tool;
  3. use PhpOffice\PhpWord\PhpWord;
  4. use PhpOffice\PhpWord\IOFactory;
  5. use PhpOffice\PhpWord\Style\Font;
  6. use PhpOffice\PhpWord\Shared\ZipArchive;
  7. use PhpOffice\PhpWord\Settings;
  8. use PhpOffice\PhpWord\Shared\Converter;
  9. use PhpOffice\PhpWord\Style\TablePosition;
  10. use think\facade\Env;
  11. use think\facade\Config;
  12. use think\File;
  13. use think\Db;
  14.  
  15. /**
  16. * Class WordUpload
  17. * [url=home.php?mod=space&uid=1507498]@Package[/url] app\common\util
  18. * word 文档上传
  19. */
  20. class WordUpload
  21. {
  22.     private $file;
  23.     private $size;
  24.     private $ext;
  25.     private $savePath = '/upload/word/';
  26.     private $errorMsg;
  27.     private $delTmp = true;
  28.      
  29.     /**
  30.     * WordUpload constructor.
  31.     * [url=home.php?mod=space&uid=952169]@Param[/url] $file [上传的文件]
  32.     * @param int $size [文件大小]
  33.     * @param string $ext [允许的后缀]
  34.     */
  35.     public function __construct($file, $size = 1024, $ext = 'docx')
  36.     {
  37.         $this->file = $file;
  38.         $this->size = $size;
  39.         $this->ext = $ext;
  40.     }
  41.     public function getHtml(){
  42.         $file = request()->file($this->file);
  43.         if (!$file instanceof File) {
  44.             $this->errorMsg = '请上传文件';
  45.             return false;
  46.         }
  47.         //上传文件 根据站点选择目录
  48.         $info = $file->validate(['size'=>$this->size,'ext'=>$this->ext])->move(Env::get('ROOT_PATH').'public/static'. $this->savePath);
  49.         if(!$info){
  50.             // 上传失败获取错误信息
  51.             $this->errorMsg = $file->getError();
  52.             return false;
  53.         }
  54.         try {
  55.             //获取文件路径
  56.             $tempDocx = Env::get('ROOT_PATH').'public/static'.$this->savePath.$info->getSaveName();
  57.             $objWriter = IOFactory::createWriter(IOFactory::load($tempDocx), 'HTML');
  58.             $tempHtml = Env::get('ROOT_PATH') . 'public/static'.$this->savePath .substr($info->getSaveName(), 0, strpos($info->getSaveName(), '.')) . '.html';
  59.             $objWriter->save($tempHtml);
  60.             $html = file_get_contents($tempHtml);
  61.             if ($this->delTmp) {
  62.                 //删除临时文件
  63.                 register_shutdown_function(function () use ($tempHtml, $tempDocx){
  64.                     unlink($tempHtml);
  65.                     unlink($tempDocx);
  66.                 });
  67.             }
  68.             $html = $this->getHtmlBody($html);
  69.             if ($html == '') {
  70.                 throw new \Exception('上传文件内容为空');
  71.             }
  72.             $html = $this->saveImage($html);
  73.             $html = $this->clearStyle($html);
  74.             $html = $this->clearSpan($html);
  75.         } catch (\Exception $e) {
  76.             $this->errorMsg = $e->getMessage();
  77.             return false;
  78.         }
  79.         return $html;
  80.     }
  81.     /**
  82.     * @param $html
  83.     * [url=home.php?mod=space&uid=155549]@Return[/url] string
  84.     * 匹配出body的内容
  85.     */
  86.     private function getHtmlBody($html) {
  87.         preg_match('/<body>([\s\S]*)<\/body>/', $html,$matches);
  88.         return isset($matches[1]) ? $matches[1] : '';
  89.     }
  90.     /**
  91.     * @param $html
  92.     * @return mixed
  93.     * 图片处理
  94.     */
  95.     private function saveImage($html){
  96.         //匹配图片
  97.         ini_set('pcre.backtrack_limit', 9999999);
  98.         preg_match_all('/<img[^>]*src="([\s\S]*?)"\/>/', $html,$imageMatches);
  99.         if (!$imageMatches[1]) {
  100.             return $html;
  101.         }
  102.         //print_r($imageMatches[1]);exit;
  103.         $imageUrl = [];
  104.         foreach ($imageMatches[1] as $image) {
  105.             $imageUrl[] = $this->saveLocalBase64Image($image);
  106.         }
  107.         return str_replace($imageMatches[1], $imageUrl, $html);
  108.     }
  109.     /**
  110.     * @param $base64_image_content
  111.     * @return string
  112.     * 保存图片到本地
  113.     */
  114.     private function saveLocalBase64Image($base64_image_content){
  115.         $imge_web_url = '';
  116.         if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
  117.             //图片后缀
  118.             $type = $result[2];
  119.             //保存位置--图片名
  120.             $image_name = date('His') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT). '.' . $type; //图片名称
  121.             $image_file_path = $this->savePath .'image/'.date('Ymd'); //static/upload/word/image/20200522
  122.             $image_file = Env::get('ROOT_PATH') .'public/static'. $image_file_path;
  123.             $imge_real_url = $image_file . DIRECTORY_SEPARATOR . $image_name;
  124.             $imge_web_url = '/static'.$image_file_path .  DIRECTORY_SEPARATOR . $image_name;
  125.             if (!file_exists($image_file)){
  126.             mkdir($image_file, 0700, true);
  127.             }
  128.             //解码
  129.             $decode = base64_decode(str_replace($result[1], '', $base64_image_content));
  130.             $res = file_put_contents($imge_real_url, $decode);
  131.             return $imge_web_url;
  132.         }
  133.         return $imge_web_url;
  134.     }
  135.     /**
  136.     * @param $content
  137.     * @return null|string|string[]
  138.     * 清除p,span标签的样式
  139.     */
  140.     private function clearStyle($content)
  141.     {
  142.         $patterns = array (
  143.             '/<(p|span)[\s\S]*?>/i',
  144.         );
  145.         return preg_replace($patterns, '<$1>', $content);
  146.     }
  147.     /**
  148.     * @param $content
  149.     * @return null|string|string[]
  150.     * 清除span标签
  151.     */
  152.     private function clearSpan($content)
  153.     {
  154.         $patterns = array (
  155.             '/<span[\s\S]*?>/i',
  156.             '/<\/span>/i',
  157.         );
  158.         return preg_replace($patterns, '', $content);
  159.     }
  160.     /**
  161.     * @return mixed
  162.     */
  163.     public function getErrorMsg()
  164.     {
  165.         return $this->errorMsg;
  166.     }
  167. }


本文网址:https://www.zztuku.com/index.php/detail-9863.html
站长图库 - 百度编辑器上传word文件转为html
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐