node.js+express+jade系列六:图片的上传

安装npm install formidable

先把文件上传到临时文件夹,再通过fs重命名移动到指定的目录即可

fs.rename即重命名,但是fs.rename不能夸磁盘移动文件,所以我们需要指定上传的临时目录要和最终目录在同一磁盘下

上传实现方法:form解析后的files是个对象,所以可以实现多文件上传

tool.uploadImg =function(req, res){
    var fs = require(‘fs‘);
    var formidable = require("formidable");
    var form = new formidable.IncomingForm();
    form.uploadDir = "./public/upload/temp/";//改变临时目录
    form.parse(req, function(error, fields, files){
        for(var key in files){
            var file = files[key];
            var fName = (new Date()).getTime();
            switch (file.type){
                case "image/jpeg":
                    fName = fName + ".jpg";
                    break;
                case "image/png":
                    fName = fName + ".png";
                    break;
                default :
                    fName =fName + ".png";
                    break;
            }
            console.log(file.size);
            var uploadDir = "./public/upload/" + fName;
            fs.rename(file.path, uploadDir, function(err) {
                if (err) {
                    res.write(err+"\n");
                    res.end();
                }
                res.write("upload image:<br/>");
                res.write("<img src=‘/imgShow?id=" + fName + "‘ />");
                res.end();
            });
        }
    });
};

显示上传后的文件

tool.imgShow = function(req, res){
    var fs = require("fs");
    var arg = tool.handleGetArg(req, res);
    var uploadDir = "./public/upload/" + arg["id"];
    fs.readFile(uploadDir, "binary", function(err, file){
        if(err){
            res.write(err+"\n");
            res.end();
        }else{
            res.write(file, "binary");
            res.end();
        }
    });
};

node.js+express+jade系列六:图片的上传

上一篇:【Javascript】之eval()


下一篇:VC++ ADO编程入门简介