我在我的Laravel应用程序中使用tinymce编辑器,我想使用图像上传插件,我向帖子控制器发出了一个帖子请求,但是当我调用url时,我得到了 methodnotallowed异常的错误
这是我的编辑代码:
tinymce.init({
selector: '#description',
convert_urls: false,
statusbar: false,
plugins: 'image code print preview fullpage searchreplace autolink directionality visualblocks visualchars fullscreen image link table charmap hr pagebreak nonbreaking toc insertdatetime advlist lists textcolor wordcount imagetools contextmenu colorpicker textpattern media ',
toolbar: 'formatselect | bold italic strikethrough forecolor backcolor | link | alignleft aligncenter alignright alignjustify | numlist bullist outdent indent | removeformat |undo redo | image code| link fontsizeselect | ',
images_upload_url: '{{url("/admin/upload")}}',
// override default upload handler to simulate successful upload
images_upload_handler: function (blobInfo, success, failure) {
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', '{{url("/admin/upload")}}');
if(xhr.status = 400){ err= "Invalid file name or Extension";}else if(xhr.status = 500){ err="Server Error";}else if(xhr.status = 403){ err="Origin Denied";}
xhr.onload = function() {
var json;
if (xhr.status != 200) {
failure('HTTP Error: ' + xhr.status +' '+err);
return;
}
json = JSON.parse(xhr.responseText);
if (!json || typeof json.location != 'string') {
failure('Invalid JSON: ' + xhr.responseText);
return;
}
success(json.location);
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);
},
});
这是控制器正在使用:
Route::prefix('admin')->group(function() {
Route::post('/upload', 'tinyupload@store');
});
我的控制器逻辑是:
public function store(Request $request)
{
// Allowed origins to upload images
$accepted_origins = array("http://localhost", "http://107.161.82.130", "http://abhidemo.com");
// Images upload path
$imageFolder = "uploads/";
reset($_FILES);
$temp = $_FILES['file']['name'];
if(is_uploaded_file($temp['tmp_name'])){
if(isset($_SERVER['HTTP_ORIGIN'])){
// Same-origin requests won't set an origin. If the origin is set, it must be valid.
if(in_array($_SERVER['HTTP_ORIGIN'], $accepted_origins)){
header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
}else{
header("HTTP/1.1 403 Origin Denied");
return;
}
}
// Sanitize input
if(preg_match("/([^\w\s\d\-_~,;:\[\]\(\).])|([\.]{2,})/", $temp['name'])){
header("HTTP/1.1 400 Invalid file name.");
return;
}
// Verify extension
if(!in_array(strtolower(pathinfo($temp['name'], PATHINFO_EXTENSION)), array("gif", "jpg", "png"))){
header("HTTP/1.1 400 Invalid extension.");
return;
}
// Accept upload if there was no origin, or if it is an accepted origin
$filetowrite = $imageFolder . $temp['name'];
$imagefull=$serverimg.$filetowrite;
move_uploaded_file($temp['tmp_name'], $filetowrite);
// Respond to the successful upload with JSON.
echo json_encode(array('location' => $imagefull));
} else {
// Notify editor that the upload failed
header("HTTP/1.1 500 Server Error");
}
}
我面临的问题是,当我尝试通过我的编辑器将图像上传到服务器时,根据我的代码和方法显示错误的类型文件错误,即使在两侧使用相同的方法POST也不允许异常
答案 0 :(得分:0)
在js中添加此代码:
<script>
tinymce.init({
selector: '#description',
convert_urls: false,
statusbar: false,
plugins: 'image code print preview fullpage searchreplace autolink directionality visualblocks visualchars fullscreen image link table charmap hr pagebreak nonbreaking toc insertdatetime advlist lists textcolor wordcount imagetools contextmenu colorpicker textpattern media ',
toolbar: 'formatselect | bold italic strikethrough forecolor backcolor | link | alignleft aligncenter alignright alignjustify | numlist bullist outdent indent | removeformat |undo redo | image code| link fontsizeselect | ',
image_title: true,
automatic_uploads: true,
images_upload_url: '{{url("/admin/upload")}}',
file_picker_types: 'image',
file_picker_callback: function(cb, value, meta) {
var input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('accept', 'image/*');
input.onchange = function() {
var file = this.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
var id = 'blobid' + (new Date()).getTime();
var blobCache = tinymce.activeEditor.editorUpload.blobCache;
var base64 = reader.result.split(',')[1];
var blobInfo = blobCache.create(id, file, base64);
blobCache.add(blobInfo);
cb(blobInfo.blobUri(), { title: file.name });
};
};
input.click();
}
});
</script><meta name="csrf-token" content="{{ csrf_token() }}" />
这在控制器中:
public function store(Request $request)
{
$file=$request->file('file');
$path= url('/uploads/').'/'.$file->getClientOriginalName();
$imgpath=$file->move(public_path('/uploads/'),$file->getClientOriginalName());
$fileNameToStore= $path;
return json_encode(['location' => $fileNameToStore]);
}