环境:
unbuntu 14.10
nodejs 0.10.35
express 4.11.2
formidable 1.0.16
kindEditor 4.1.10
webStorm 8
1.通过IDE或终端创建一个名称为test的工程
2.编辑package.json添加formidable依赖,这里使用的是1.0.16版本,之后通过终端执行npm install完成依赖的安装
3.将kindEditor整个目录放到test/public/lib下
4.修改index.ejs和index.js文件
index.ejs中整合kindEditor:
设置kindEditor的uploadJson为nodejs所提供的处理图片上传的路由url这里用的是/uploadImg
index.js中添加处理图片上传的路由url:
添加/uploadImg对应的post处理方式,
代码如下:
index.js
复制代码 代码如下:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link href='https://www.jb51.net/stylesheets/style.css' />
<script charset="utf-8" src="https://www.jb51.net/lib/kindeditor-4.1.10/kindeditor.js"></script>
<script charset="utf-8" src="https://www.jb51.net/lib/kindeditor-4.1.10/lang/zh_CN.js"></script>
<script>
var options = {
uploadJson: '/uploadImg'
};
KindEditor.ready(function(K) {
window.editor = K.create('#editor', options);
});
</script>
</head>
<body>
<h1><%= title %></h1>
<textarea>
<strong>HTML内容</strong>
</textarea>
</body>
</html>
index.js
复制代码 代码如下:
var express = require('express');
var router = express.Router();
var formidable = require('formidable');
/* GET home page. */
router.get('https://www.jb51.net/', function(req, res, next) {
res.render('index', { title: '图片上传' });
});
router.post('/uploadImg', function(req, res, next) {
var form = new formidable.IncomingForm();
form.keepExtensions = true;
form.uploadDir = __dirname + '/../public/upload';
form.parse(req, function (err, fields, files) {
if (err) {
throw err;
}
var image = files.imgFile;
var path = image.path;
path = path.replace('/\\/g', 'https://www.jb51.net/');
var url = '/upload' + path.substr(path.lastIndexOf('https://www.jb51.net/'), path.length);
var info = {
"error": 0,
"url": url
};
res.send(info);
});
});
module.exports = router;
之后通过IDE或终端启动test工程,通过:3000访问页面就可以上传图片了
您可能感兴趣的文章: