使用formidable上传文件并显示时,碰到fs.renameSync报错,在网络上找到两种方法
var fs = require(‘fs’);
var http = require(‘http’);
var formidable = require(“formidable”);
http.createServer(function(req, res) {
if(req.url == '/upload' && req.method.toLowerCase() == 'post') {
// parse a file upload
var form = new formidable.IncomingForm();
form.uploadDir = '/tmp';
form.parse(req, function(err, fields, files) {
console.log(files.upload.path);
// fs.renameSync(files.upload.path, "/tmp/test.jpg");
var readStream = fs.createReadStream(files.upload.path);
var writeStream = fs.createWriteStream("/tmp/test.jpg");
readStream.pipe(writeStream);
readStream.on('end', function() {
fs.unlinkSync(files.upload.path);
});
res.writeHead(200, {
"Content-Type": "text/html"
});
res.write("received image:<br/>");
res.write("<img src='/show' />");
res.end();
});
return;
}
if(req.url == "/show") {
fs.readFile("/tmp/test.jpg", "binary", function(error, file) {
if(error) {
res.writeHead(500, {
"Content-Type": "text/plain"
});
res.write(error + "\n");
res.end();
} else {
res.writeHead(200, {
"Content-Type": "image/png"
});
res.write(file, "binary");
res.end();
}
});
return;
}
// show a file upload form
res.writeHead(200, {
'content-type': 'text/html'
});
res.end(
'<form action="/upload" enctype="multipart/form-data" method="post">' +
'<input type="text" name="title"><br>' +
'<input type="file" name="upload" multiple="multiple"><br>' +
'<input type="submit" value="Upload">' +
'</form>'
);
}).listen(8011);
console.log("Server running at http://" + getIPv4() + ":8011/");
function getIPv4() {
var interfaces = os.networkInterfaces(); //获取网络接口列表
var ipv4s = []; //同一接口可能有不止一个IP4v地址,所以用数组存
Object.keys(interfaces).forEach(function(key) {
interfaces[key].forEach(function(item) {
//跳过IPv6 和 '127.0.0.1'
if('IPv4' !== item.family || item.internal !== false) return;
ipv4s.push(item.address); //可用的ipv4s加入数组
console.log(key + '--' + item.address);
})
})
return ipv4s[0]; //返回一个可用的即可
}