Node.js 上传文件formidable时使用fs.renameSync报错

使用formidable上传文件并显示时,碰到fs.renameSync报错,在网络上找到两种方法
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]; //返回一个可用的即可
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值