需求描述
使用富文本编辑工具summernote进行内容编辑保存。(本文的后台使用的是thinkPHP6框架)
重点:
- 通过数据库动态获取保存的内容能够正常渲染(htmlspecialchars_decode)。
- 引入图片后上传到后台,后台返回url,方便保存到数据库。
html部分
<div id="summernote">{:htmlspecialchars_decode($product.product_desc)}</div>
JavaScript部分
//summernote官网:https://summernote.org/examples/#example
$(document).ready(function() {
let $summernote = $('#summernote').summernote({
height: 150,
callbacks: {
//将图片上传到服务器或者第三方平台
onImageUpload: function(files) {
var data = new FormData();
data.append("product_img", files[0]);
$.ajax({
data : data,
type : "POST",
url : "/admin/product/uploadImg", //图片上传出来的url,返回的是图片上传后的路径,http格式
cache : false,
contentType : false,
processData : false,
dataType : "json",
success: function(res) {
if (res.code==0) {
$summernote.summernote('insertImage', res.data,'img');
} else {
alert(res.msg);//上传失败
}
},
error:function(){
alert("上传失败,请联系管理员");
}
});
},
}
});
$("#toEdit").click(function () {
//获取产品详情(富文本)的内容
let desc = $('#summernote').summernote('code');
// console.log(desc);return
let data = {
'id': $("input[name=product_id]").val(),
'product_name': $("input[name=product_name]").val(),
'product_desc':desc,
};
console.log(data)
$.ajax({
data : data,
type : "POST",
url : "/admin/product/updateProduct", //图片上传出来的url,返回的是图片上传后的路径,http格式
success: function(res) {
location.reload()
},
error:function(){
alert("编辑失败,请联系管理员");
}
})
})
});
PHP部分
/**
* 产品详情富文本上传文件
* @return \think\response\Json
*/
public function uploadImg()
{
// 获取表单上传文件
$file = request()->file('product_img');
try{
// 上传到本地服务器
//这里的public是在config/filesystem.php配置文件中配置。相当于保存到 public/storage/product目录下
$saveName = \think\facade\Filesystem::disk('public')->putFile( 'product', $file,'md5');
$path = sprintf("/storage/%s",$saveName);
$path = str_replace('\\', '/', $path);
return $this->returnJson($path,0,"上传成功");
} catch (Exception $e) {
return $this->returnJson("",1,"上传失败:".$e->getMessage());
}
}