用我如今最常使用的php框架fastadmin举例子,固然thinkphp或者原生php也是一样的原理,你们理解思路就行了、php
一、thinkphp使用composer安装phpword插件(这个插件可以把word转为html)html
composer require phpoffice/phpword
安装完成以后的文件在vender目录下node
二、打开require统一管理后台插件的jsjquery
引入咱们须要的ajaxfileupload.js插件(这个插件容许文件经过ajax上传到服务器,而不是form表单)git
'ajaxfileupload':'../libs/ajaxfileupload/ajaxfileupload',
三、以新增新闻的编辑器为例,打开github
在开头载入须要的组件ajax
define(['jquery', 'bootstrap', 'backend', 'table', 'form','summernote','layer','ajaxfileupload'], function ($, undefined, Backend, Table, Form,summernote,layer,ajaxfileupload) {
而后修改add方法thinkphp
add: function () { Controller.api.bindevent(); var imageButton = function (context) { var ui = $.summernote.ui; var button = ui.button({ contents: '<i class="fa fa-file-image-o"/>', tooltip: __('Choose'), click: function () { parent.Fast.api.open("general/attachmentlect?element_id=&multiple=true&mimetype=image/*", __('Choose'), { callback: function (data) { var urlArr = data.url.split(/\,/); $.each(urlArr, function () { var url = Fast.api.cdnurl(this); context.invoke('editor.insertImage', url); }); } }); return false; } }); return button.render(); }; var attachmentButton = function (context) { var ui = $.summernote.ui; var button = ui.button({ contents: '<i class="fa fa-file"/>', tooltip: __('Choose'), click: function () { parent.Fast.api.open("general/attachmentlect?element_id=&multiple=true&mimetype=*", __('Choose'), { callback: function (data) { var urlArr = data.url.split(/\,/); $.each(urlArr, function () { var url = Fast.api.cdnurl(this); var node = $("<a href='" + url + "'>" + url + "</a>"); context.invoke('insertNode', node[0]); }); } }); return false; } }); return button.render(); }; // 新增编辑器导入word功能
var wordBtn = function (context) { var ui = $.summernote.ui; var button = ui.button({ contents: '<i class="fa fa-file-word-o"/>', tooltip: '导入word', click: function () { // 点击以后的操做
layer.open({ type: 1, skin: 'layui-layer-rim', //加上边框
area: ['420px', '160px'], //宽高
content: '<input type="file" id="file" name="file" title="上传word" value="" ><br/><input type="button" value="上传" id="submit" />' }); } }); return button.render(); // return button as jquery object
}; $(".summernote,.editor", $('form')).summernote({ height: 250, lang: 'zh-CN', fontNames: [ 'Arial', 'Arial Black', 'Serif', 'Sans', 'Courier',
'Courier New', 'Comic Sans MS', 'Helvetica', 'Impact', 'Lucida Grande',
"Open Sans", "Hiragino Sans GB", "Microsoft YaHei",
'微软雅黑', '宋体', '黑体', '仿宋', '楷体', '幼圆', ], fontNamesIgnoreCheck: [ "Open Sans", "Microsoft YaHei",
'微软雅黑', '宋体', '黑体', '仿宋', '楷体', '幼圆' ], toolbar: [ ['style', ['style', 'undo', 'redo']], ['font', ['bold', 'underline', 'strikethrough', 'clear']], ['fontname', ['color', 'fontname', 'fontsize']], ['para', ['ul', 'ol', 'paragraph', 'height']], ['table', ['table', 'hr']], ['insert', ['link', 'picture', 'video']], ['select', ['image', 'attachment']], ['view', ['fullscreen', 'codeview', 'help','word']], ], buttons: { image: imageButton, attachment: attachmentButton, word:wordBtn }, dialogsInBody: true, followingToolbar: false, callbacks: { onChange: function (contents) { $(this).val(contents); $(this).trigger('change'); }, onInit: function () { }, onImageUpload: function (files) { var that = this; //依次上传图片
for (var i = 0; i < files.length; i++) { Upload.api.send(files[i], function (data) { var url = Fast.api.cdnurl(data.url); $(that).summernote("insertImage", url, 'filename'); }); } } } }); // 点击上传按钮,发送ajax,上传word文档,并获取到返回的html地址 // 动态生成的元素须要使用在document上加点击事件
$(document).on('click','#submit',function(){ var path = $('#file').val(); if ($.trim(path) == "") { alert("请选择要上传的文件"); return; } $.ajaxFileUpload({ url: 'form', //这里是服务器处理的代码
type: 'post', secureuri: false, //通常设置为false
fileElementId: 'file', // 上传文件的id、name属性名
dataType: 'json', //返回值类型,通常设置为json、application/json
success: function (data, status) { console.log('success') }, error:function(data, status, e){ console.log('error') var responseText = data.responseText; // console.log(responseText); // 把html赋值给富文本,,并关闭layui
$('.layui-layer-close').click(); $(".summernote,.editor", $('form')).summernote('code',responseText); } }); }); },
四、修改控制器json
use PhpOffice\PhpWord\PhpWord; ...
public function form(){ // 接收表单上传的文件,并存储到服务器中
$file = $_FILES['file']['tmp_name'];//上传的文件
move_uploaded_file($file,"/words/res.docx"); // 使用phpword将word转为html
$phpWord = IOFactory::load('/words/res.docx'); $xmlWriter = IOFactory::createWriter($phpWord, "HTML"); $resPath = '/words/res.html'; $xmlWriter->save($resPath); $html = file_get_contents($resPath); return $html; }
public function base64_image_content($base64_image_content,$path){ //匹配出图片的格式
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){ $type = $result[2]; $new_file = $path."/".date('Ymd',time())."/"; if(!file_exists($new_file)){ //检查是否有该文件夹,若是没有就建立,并给予最高权限
mkdir($new_file, 0700); } $new_file = $new_file.time().".{$type}"; if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){ return '/'.$new_file; }else{ return false; } }else{ return false; } }
public function write() { if (!$this->element instanceof ImageElement) { return ''; } $content = ''; $imageData = $this->element->getImageStringData(true); if ($imageData !== null) { $styleWriter = new ImageStyleWriter($this->element->getStyle()); $style = $styleWriter->write(); $imageData = 'data:' . $this->element->getImageType() . ';base64,' . $imageData; // 一、获取到项目根目录 // ---- D:/phpstudy_pro/WWW/word/vendor/phpoffice/phpword/src/PhpWord/Writer/HTML/Element/
$path = str_replace('\\','/',realpath(dirname(__FILE__).'/'))."/"; // --- D:/phpstudy_pro/WWW/word
$path = explode('/vendor/phpoffice/phpword/src/PhpWord/Writer/HTML/Element/',$path)[0]; // 二、调用在类中新增的方法,将图片存入 D:/phpstudy_pro/WWW/word/public/word_images
$imageData = $this->element->base64_image_content($imageData, $path.'/public/word_images'); // 三、替换为html里要显示的格式,替换时根据项目的默认路径灵活修改
$imgPath = str_replace($path."/","",$imageData); // 原生php版本 // $imgPath = str_replace($path."/public/","",$imageData); // thinkphp版本
$content .= $this->writeOpening(); // 四、返回
$content .= "<img border=\"0\" style=\"{$style}\" src=\"{$imgPath}\"/>"; $content .= $this->writeClosing(); } return $content; }