nodejs上传图片

方法一:

exports.upload = function(req, res){
    //引入必要的包
    var fs = require('fs');
    var path = require('path');

    //获取上传的文件名称,路径
    var fileName = req.files.image.filename;
    var tmp_path = req.files.image.path;
    var target_path = __dirname + "/upload/" + fileName;

    //判断文件是否存在
    path.exists(tmp_path, function(isExist){
        if (isExist){
            //在这部执行将tmp下的图片重名到指定的目录下
            fs.rename(tmp_path, target_path, function(err){
                if (err){
                    console.dir(err); //如果这里打印出错误,请查看target_path路径
                };
            });
        } else {
            console.log("No");
        }
    });

    console.dir(req.files);

    //Redirec index.
    res.redirect("/");
}

方法二:

exports.upload = function(req, res){
    var fs = require('fs');
    var path = require('path');
    var util = require('util');
    var fileName = req.files.image.filename;
    var tmp_path = req.files.image.path;
    var target_path = __dirname + "/upload/" + fileName;

    path.exists(tmp_path, function(isExist){
        if (isExist){
            ins = fs.createReadStream(tmp_path);
            ous = fs.createWriteStream(__dirname + "/upload/" + fileName);
            util.pump(ins, ous, function(err){
                console.dir(err);
                });
        } else {
            console.log("No");
        }
    });

    console.dir(req.files);
    //Redirec index.
    res.redirect("/");
}

注意:方法一可以在使用完后,不用删除tmp下的图片,它会自动删除tmp下的文件。但是方法二,要手动删除tmp下的图片。

发表评论

电子邮件地址不会被公开。

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>