使用keystone時遇到一個問題:keystone後臺使用tinymce作富文本編輯器,但其只提供了插入網絡圖片的功能,而不能上傳和管理本地圖片,好在keystone提供了選項來爲tinymce添加插件,so~開搞html
下載插件並放到靜態目錄下git
在keystone.init()
中增長以下配置項:github
{ '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' }, // 上傳圖片插件 } }
在路由文件中增長以下代碼:express
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
中間件json
models/FileUpload.js
:api
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, }); }) }