nodejs+express整合kindEditor實現圖片上傳

kindEditor官網上中提供了ASP,ASP.NET,JSP相關的整合應用,http://kindeditor.net/docs/upload.html能夠參照實現nodejs的整合,發現實用nodejs更簡單 css

環境:
unbuntu 14.10
nodejs 0.10.35
express 4.11.2
formidable 1.0.16
kindEditor 4.1.10
webStorm 8 html

1.經過IDE或終端建立一個名稱爲test的工程 node

2.編輯package.json添加formidable依賴,這裏使用的是1.0.16版本,以後經過終端執行npm install完成依賴的安裝 web

3.將kindEditor整個目錄放到test/public/lib下 express

4.修改index.ejs和index.js文件
index.ejs中整合kindEditor:
       設置kindEditor的uploadJson爲nodejs所提供的處理圖片上傳的路由url這裏用的是/uploadImg
index.js中添加處理圖片上傳的路由url:
       添加/uploadImg對應的post處理方式,
代碼以下: npm

index.ejs json

<!DOCTYPE html>
<html>
  <head>
    <title><%= title %></title>
    <link rel='stylesheet' href='/stylesheets/style.css' />
      <script charset="utf-8" src="/lib/kindeditor-4.1.10/kindeditor.js"></script>
      <script charset="utf-8" src="/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 id="editor" name="content" style="width:700px;height:300px;">
        &lt;strong&gt;HTML內容&lt;/strong&gt;
    </textarea>
  </body>
</html>
index.js
var express = require('express');
var router = express.Router();
var formidable = require('formidable');

/* GET home page. */
router.get('/', 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', '/');
        var url = '/upload' + path.substr(path.lastIndexOf('/'), path.length);

        var info = {
            "error": 0,
            "url": url
        };
        res.send(info);
    });
});

module.exports = router;
以後經過IDE或終端啓動test工程,經過http://localhost:3000訪問頁面就能夠上傳圖片了
相關文章
相關標籤/搜索