写在前面
①定义路由
Route::post('article/image/upload', 'ArticleController@imageUpload');
②修改配置文件config/filesystems.php,其他默认就好。
// 'default' => env('FILESYSTEM_DRIVER', 'local'),
'default' => env('FILESYSTEM_DRIVER', 'public'),
③上传的图片无法访问除 public 以外的目录,所以要设置上传文件的软链接,控制台执行以下命令。
php artisan storage:link
1、首先将资源文件引入,上方官方文档中已经有了,这里不再赘述,先放HTML代码。
html代码,head部分放csrf_token,页面上用form-group包裹只是为了样式,也可以通过margin等实现
如果将编辑器放在form中会出现“Uncaught TypeError: Cannot read property ‘type’ of undefined”和”Assertion failed: Input argument is not an HTMLInputElement“等错误。
<meta name="csrf-token" content="{{csrf_token()}}">
@section('main')
<div class="col-md-8 col-md-offset-2" style="margin-top: 20px;">
<div class="form-group" id="title">
<label>标题</label>
<input name="title" type="text" class="form-control" placeholder="这里是标题">
</div>
<div class="form-group">
<label>内容</label>
<div id="editor">
</div>
</div>
<button type="button" class="btn btn-default pull-right" onclick="releaseArticle()">提交</button>
</div>
@endsection
2、JS代码
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var E = window.wangEditor
var editor = new E('#editor')
// 配置服务器端地址
editor.customConfig.uploadImgServer = "{{url('article/image/upload')}}";
// 设置文件的name值
editor.customConfig.uploadFileName = 'wangEditorImage[]';
//设置headers
editor.customConfig.uploadImgHeaders = {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
};
// 将图片大小限制为 3M
editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024
// 限制一次最多上传 5 张图片
editor.customConfig.uploadImgMaxLength = 5
//自定义处理
editor.customConfig.uploadImgHooks = {
success: function (xhr, editor, result) {
console.log("上传成功");
},
fail: function (xhr, editor, result) {
console.log("上传失败,原因是" + result);
},
error: function (xhr, editor) {
console.log("上传出错");
},
timeout: function (xhr, editor) {
console.log("上传超时");
},
// 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式,可使用该配置
// (但是,服务器端返回的必须是一个 JSON 格式字符串!!!否则会报错)
customInsert: function (insertImg, result, editor) {
// insertImg 是插入图片的函数,editor 是编辑器对象,result 是服务器端返回的结果
for (let i = 0; i < result.length; i++) {
let url = result[i]
insertImg(url)
}
}
};
editor.create()
//发布文章
function releaseArticle() {
let title = $("input[name=title]").val();
let article = editor.txt.html();
$.ajax({
url: " {{ url('article/add') }}",
method: 'post',
dataType: 'json',
data: {
'title': title,
'article': article
},
success: function (data) {
if (data.error != 0) {
addErrorTips(data);
return;
}
window.location.href = "/index";
}, error: function (data) {
addErrorTips(JSON.parse(data.responseText))
}
});
}
// 动态在页面添加错误提示信息
function addErrorTips(data) {
str = '<div class="alert alert-danger" role="alert">';
str += '<li>' + data.message + '</li>';
str += '</div>';
$(".alert").remove();
$("#title").before(str);
}
</script>
3、后台代码
//发布文章
public function add(Request $request)
{
if ($request->isMethod('post')) {
$data = $request->all();
$data['uid'] = $this->getCurrentUid();
if (Article::create($data)) {
return json_encode(array('error' => '0'));
} else {
return json_encode(array('message' => '文章发布失败'));
}
} else {
return view('article/add');
}
}
//上传图片
public function imageUpload(Request $request)
{
$images = $request->file('wangEditorImage');
if ($images != null && count($images) > 0) {
$url = array();
foreach ($images as $key => $val) {
$url[] = asset('storage/' . $val->storePublicly(md5(time())));
}
}
return json_encode($url);
}
4、页面效果