以下是 `wangEditor-mobile` 开发时,测试上传图片的服务器端代码(重点部分),也可以直接[点击这里](https://github.com/wangfupeng1988/wangEditor-mobile/blob/master/server.js)查看完整的server端代码。
```
// nodejs 代码
if (req.url === '/upload' && req.method.toLowerCase() === 'post') {
// 使用第三方的 formidable 插件初始化一个 form 对象
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
if (err) {
return console.log('formidable, form.parse err');
}
var file = files['wangEditorMobileFile'];
var tempfilepath = file.path;
var type = file.type;
var filename = file.name;
var extname = filename.lastIndexOf('.') >= 0
? filename.slice(filename.lastIndexOf('.') - filename.length)
: '';
if (extname === '' && type.indexOf('/') >= 0) {
extname = '.' + type.split('/')[1];
}
filename = Math.random().toString().slice(2) + extname;
var filenewpath = uploadfolderpath + '/' + filename;
fs.rename(tempfilepath, filenewpath, function (err) {
var result = '';
if (err) {
console.log('fs.rename err');
result = 'error|save error';
} else {
console.log('fs.rename done');
result = 'http://localhost:' + port + '/' + uploadfoldername + '/' + filename;
}
res.writeHead(200, {
'Content-type': 'text/html'
});
res.end(result);
});
});
}
```