最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Nodejs环境配置UEditor文件图片上传的例子
时间:2022-06-25 19:38:26 编辑:袖梨 来源:一聚教程网
由于UEditor官网没有提供Nodejs版,于是自己尝试进行修改。先根据PHP版查看所有的请求,得到的action参数值包括config(配置文件)、uploadimage(图片上传)、listimage(在线管理)、catchimage(抓取图片),所以只需要重写这4个请求就基本上实现了我们的需求。
1、首先修改UEditor的ueditor.config.js中的serverUrl属性:
serverUrl:'/ue/uploads'
2、将ueditor/php/config.json文件名重置为config.js,并将其移动到ueditor目录下;
3、创建服务端方法/ue/uploads?action=xxxx,直接上代码(注意:上传功能使用了connect-busboy中间件)
/**
* Created by Satrong on 2014/7/27.
* UEditor 上传 服务端 控制器
*/
var http = require('http');
var fs = require('fs');
var path = require('path');
var url = require('url');
var uploadsPath = path.resolve('uploads') + '/';//存储图片的路径
var action = {
/// 上传图片
uploadimage: function (req, res) {
var fstream;
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
var filesize = 0;
var ext = path.extname(filename);
var newFilename = (new Date() - 0) + ext;
fstream = fs.createWriteStream(uploadsPath + newFilename);
file.on('data', function (data) {
filesize = data.length;
});
fstream.on('close', function () {
res.send(JSON.stringify({
"originalName": filename,
"name": newFilename,
"url": '/uploads/' + newFilename,
"type": ext,
"size": filesize,
"state": "SUCCESS"
}));
});
file.pipe(fstream);
});
},
/// 获取配置文件
config: function (req, res) {
return res.json(require('/ueditor/config.js'));
},
/// 在线管理
listimage: function (req, res) {
fs.readdir(uploadsPath, function (err, files) {
var total = 0, list = [];
files.sort().splice(req.query.start, req.query.size).forEach(function (a, b) {
/^.+...+$/.test(a) &&
list.push({
url: '/uploads/' + a,
mtime: new Date(fs.statSync(uploadsPath + a).mtime).getTime()
});
});
total = list.length;
res.json({state: total === 0 ? 'no match file' : 'SUCCESS', list: list, total: total, start: req.query.start});
});
},
/// 抓取图片(粘贴时将图片保存到服务端)
catchimage: function (req, res) {
var list = [];
req.body.source.forEach(function (src, index) {
http.get(src, function (_res) {
var imagedata = '';
_res.setEncoding('binary');
_res.on('data', function (chunk) {
imagedata += chunk
});
_res.on('end', function () {
var pathname = url.parse(src).pathname;
var original = pathname.match(/[^/]+.w+$/g)[0];
var suffix = original.match(/[^.]+$/)[0];
var filename = Date.now() + '.' + suffix;
var filepath = uploadsPath + 'catchimages/' + filename;
fs.writeFile(filepath, imagedata, 'binary', function (err) {
list.push({
original: original,
source: src,
state: err ? "ERROR" : "SUCCESS",
title: filename,
url: '/uploads/catchimages/' + filename
});
})
});
})
});
var f = setInterval(function () {
if (req.body.source.length === list.length) {
clearInterval(f);
res.json({state: "SUCCESS", list: list});
}
}, 50);
}
};
module.exports = {
"get:/ue/uploads": function (req, res) {
action[req.query.action](req, res);
},
"post:/ue/uploads": function (req, res) {
action[req.query.action](req, res);
}
}
以上代码关键部分在action对象中,其余部分可根据自己项目的情况做调整。(服务端没有做上传文件的限制)