【发布时间】:2019-12-06 04:07:01
【问题描述】:
我正在创建一个博客站点,我可以使用 tinymce 的富文本编辑器将图像上传到它,但图像的预览不会显示在 textarea 中。 (尽管如果我还是上传了图片,我可以在 blogfeed 中完美地看到它)。
我怀疑我在 MVC 框架中实现 tinymce 的方式存在问题(udemy 上的 brad traversy 框架)。因为当我查看图像的文件路径时,它们是不同的。
"<img src="http//localhost/mywebsite/content/images/image.jpg>"。 (图片来自博客源)
"<img src="http//localhost/mywebsite/posts/content/images/image.jpg"。 (图片来自 tinymce 编辑器)
由于某种原因,当图像加载到 tinymce 编辑器时,控制器被包含在内。我试着弄乱应该保存图像的位置,如果我将其设置为$imageFolder = "images/";,那么我可以在博客提要中看到图像,但不能在预览中看到。如果我设置了$imageFolder = "../images/";,那么可以在预览中看到图像,但在 blogfeed 中看不到。
我还尝试定义一个常量路径,“定义(“IMGROOT”,/path/to/my/site)”,然后设置$imageFolder = IMGROOT . 'content/images";,但随后出现错误“不允许加载本地资源”和我不太热衷于规避这一点,因为这可能是我的博客发布后不加载本地资源的一个很好的理由。
上传.php:
<?php
//upload images
header('Content-Type: application/json');
/***************************************************
* Only these origins are allowed to upload images *
***************************************************/
$accepted_origins = array("http://localhost", "http://192.168.1.1", "http://example.com");
/*********************************************
* Change this line to set the upload folder *
*********************************************/
$imageFolder = "images/";
$temp = current($_FILES);
// Accept upload if there was no origin, or if it is an accepted origin
$filetowrite = $imageFolder . $temp['name'];
move_uploaded_file($temp['tmp_name'], $filetowrite);
// Respond to the successful upload with JSON.
// Use a location key to specify the path to the saved image resource.
// { location : '/your/uploaded/image/file'}
echo json_encode(array('location' => $filetowrite));
上传处理程序:
tinymce.init({
selector: '#tinymcebody',
plugins: "image",
images_upload_url: '<?php echo URLROOT;?>/upload.php',
images_upload_handler: function (blobInfo, success, failure) {
var xhr;
var formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', '<?php echo URLROOT;?>/upload.php');
xhr.onload = function() {
var json;
if (xhr.status != 200) {
failure('HTTP Ereror: ' + xhr.status);
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());
console.log(formData);
xhr.send(formData);
}
});
【问题讨论】: