搭建node远程服务器
1. 在根目录下安装node稳定版
2. 创建服务器
var http = require('http');
var formidable = require('formidable');
var fs = require('fs');
var path = require('path')
var Util = require('./util.js')
http.createServer(function(req, res) {
if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
var oldpath = files.filetoupload.path;
var newpath = '/home/qiuzhilin/www/blue-pi-upload.tianqi.cn/upload/' + files.filetoupload.name;
fs.rename(oldpath, newpath, function(err) {
if (err) throw err;
// 获取文件名
var txtname = path.basename(newpath);
var basename = path.basename(newpath,'.txt')
// 获取网络路径
oldpath = path.join('https://blue-pi-upload.tianqi.cn/upload/',txtname)
res.write(oldpath);
// 读取文件内容
fs.readFile(newpath, (err, data) => {
if (err) throw err;
data = data.toString()
data = Util.formateData(data)
data = JSON.stringify(data)
fs.writeFile('../blue-pi-upload.tianqi.cn/upload/json/' + basename + '.json' , data, (err) => {
if (err) throw err;
console.log('The file has been saved!');
});
});
res.end();
});
});
} else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}
}).listen(10087);
3. 运行服务器
- 打开Xshell,进入服务器
- node ~/demo.js
4. 打开chrome,地址栏http://IP:10087/
5. 文件上传到
6. 访问https://blue-pi-upload.tianqi.cn/upload/json/hainan.json获取数据