這篇文章帶給大家的內容是關於keystone.js後台編輯器中上傳圖片的實作方法,有一定的參考價值,有需要的朋友可以參考一下,希望對你有幫助。
使用keystone時遇到一個問題:keystone後台使用tinymce做富文本編輯器,但其只提供了插入網絡圖片的功能,而不能上傳和管理本地圖片,好在keystone提供了選項來為tinymce新增外掛程式
下載外掛程式並放到靜態目錄下
在keystone.init()
中增加以下設定項:
{ 'wysiwyg additional plugins': 'uploadimage', 'wysiwyg additional buttons': 'uploadimage', 'wysiwyg additional options': { 'uploadimage_form_url': '/api/admin/upload-image', //上传图片的API 'relative_urls': false, 'external_plugins': { 'uploadimage': '/js/uploadimage/plugin.min.js' }, // 上传图片插件 } }
在路由檔案中增加以下程式碼:
var router = express.Router(); var keystone = require('keystone'); var importRoutes = keystone.importer(__dirname); var routes = { api: importRoutes('./api'), }; router.post('/api/admin/upload-image', keystone.middleware.api, routes.api.upload_image); module.exports = router;
我們將API放到api/upload_image.js
中,注意新增的API需要新增keystone.middleware. api
中間件
models/FileUpload.js
:
var keystone = require('keystone'); var Types = keystone.Field.Types; /** * File Upload Model * =========== * A database model for uploading images to the local file system */ var FileUpload = new keystone.List('FileUpload'); var myStorage = new keystone.Storage({ adapter: keystone.Storage.Adapters.FS, fs: { path: keystone.expandPath('public/uploads'), // required; path where the files should be stored publicPath: 'uploads', // path where files will be served } }); FileUpload.add({ name: { type: Types.Key, index: true}, file: { type: Types.File, storage: myStorage }, createdTimeStamp: { type: String }, alt1: { type: String }, attributes1: { type: String }, category: { type: String }, //Used to categorize widgets. priorityId: { type: String }, //Used to prioritize display order. parent: { type: String }, children: { type: String }, url: {type: String}, fileType: {type: String} }); FileUpload.defaultColumns = 'name'; FileUpload.register();
api/upload_image.js
實作細節:
var keystone = require('keystone'), fs = require('fs'), path = require('path'); var FileData = keystone.list('FileUpload'); module.exports = function (req, res) { var item = new FileData.model(), data = (req.method == 'POST') ? req.body : req.query; // keystone采用的老版multer来解析文件,根据req.files.file.path将文件从缓冲区复制出来 fs.copyFile(req.files.file.path, path.join(__dirname, '../../public/uploads', req.files.file.name), function (err) { var sendResult = function () { if (err) { res.send({ error: { message: err.message } }); } else { // 按插件要求的返回格式返回URL res.send({ image: { url: "\/uploads\/" + req.files.file.name } }); } }; // TinyMCE upload plugin uses the iframe transport technique // so the response type must be text/html res.format({ html: sendResult, json: sendResult, }); }) }
相關推薦:
請教編輯器ckeditor開啟圖片上傳後 upload.php文件上傳出錯
以上是keystone.js後台編輯器中上傳圖片的實作方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!