登录
注册
node.js 学习社区
图片上传及数据库增加对应记录

烧饼大漠

2014-12-01 01:06

这两天做了一个图片上传功能,很庆幸express 3.x版本文件上传及nodejs 1.0xx版本文件操作功能支持的很不错。

前端(不能直接copy代码,直接转换html):

 form method="post" enctype="multipart/form-data" action="/userimage_upload" 
    div class="modal-body"

        input class="customfile-input" type="file" name="user_file"
    /div
    div class="modal-footer"
        button class="btn" data-dismiss="modal" aria-hidden="true"关闭/button
        button class="btn btn-primary" type="submit"上传/button
    /div
/form 

后端(包括引用mongoose连接池全贴上来):

 var status = require('./../status');
var mongoose = status.mongoose;
var db = status.db;
var Schema = mongoose.Schema;
var filter = require("./../moudels/filter.js");
var Removes_userlogo = db.model('remove_user_logo', new Schema({
    innerdate: {
        type: Date,
    default:
        Date.now
    },
    update: {
        type: Date,
    default:
        Date.now
    },
    user: String,
    name: String
}));
// 移动文件需要使用fs模块
var fs = require('fs');
module.exports = function (app) {
    app.post('/userimage_upload', filter.authorize, function (req, res) {
        // 获得文件的临时路径
        var tmp_path = req.files.user_file.path;
        var target_file = './public/user/logo/' + req.session.name;
        var target_path = target_file + '/user';
        var newIname_arry = req.files.user_file.name.split('.');
        var tem_extension = newIname_arry[newIname_arry.length - 1]; //后缀名
        fs.exists(target_file, function (exist) {
            if (!exist) {
                fs.mkdirSync(target_file);
            }
            fs.exists(target_path + '.' + tem_extension, function (exist) {
                if (exist) {
                    fs.exists(target_file + "/remove", function (exist) {
                        if (exist) {
                            takefile(target_path, target_file, tmp_path, tem_extension, function (remove_name) {
                                insertRemoves_userlogo(req, res, remove_name);
                                res.send({
                                    status: 0
                                });
                            });
                        } else {
                            fs.mkdirSync(target_file + "/remove");
                            takefile(target_path, target_file, tmp_path, tem_extension, function (remove_name) {
                                insertRemoves_userlogo(req, res, remove_name);
                                res.send({
                                    status: 0
                                });
                            });
                        }
                    });
                } else {
                    // 移动文件
                    fs.rename(tmp_path, target_path + '.' + tem_extension, function (err) {
                        if (err) {
                            throw err;
                            res.send({
                                status: 1
                            });
                        }
                        fs.unlink(tmp_path, function () {
                            if (err) throw err;
                            res.send({
                                status: 0
                            }); //res.send('File uploaded to: ' + target_path + ' - ' + req.files.thumbnail.size + ' bytes');
                        });
                    });
                }
            });
        });
    });
}; 
//文件操作 具体操作 //保留文件地址 回收站文件夹地址 临时文件地址 临时文件后缀名 自定义回调函数
 var takefile = function (target_path, target_file, tmp_path, tem_extension, func) {
    var now = new Date();
    var rOption = {
        flags: 'r',
        encoding: null,
        mode: 0666
    }

    var wOption = {
        flags: 'a',
        encoding: null,
        mode: 0666
    }
    var namefiles = fs.readdirSync(target_file);
    var remove_extension = "";
    for (i in namefiles) {
        if (namefiles[i].indexOf("user.") == 0) {
            var arr = namefiles[i].split(".");
            remove_extension = arr[arr.length - 1];
            break;
        }
    }
    var remove_name = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate() + "  " + now.getHours() + "_" + now.getMinutes() + "_" + now.getSeconds() + "_" + now.getMilliseconds();
    var old_file = fs.createReadStream(target_path + '.' + remove_extension, rOption);
    var new_file = fs.createWriteStream(target_file + "/remove/" + remove_name + "." + remove_extension, wOption);
    old_file.on('data', function (data) {
        new_file.write(data);
    });
    old_file.on('end', function () {
        new_file.end();
        fs.unlink(target_path + '.' + tem_extension, function (err) {

        });
        // 移动文件
        fs.rename(tmp_path, target_path + '.' + tem_extension, function (err) {
            if (err) {
                throw err;
                res.send({
                    status: 1
                });
            }
            fs.unlink(tmp_path, function () {
                if (err) throw err;
                func(remove_name);
            });
        });
    });
}
//remove数据库增加
var insertRemoves_userlogo = function (req, res, name) {
    var removes = new Removes_userlogo({
        user: req.session.name,
        name: name,
        innerdate: Date(),
        update: Date()
    });
    removes.save(function (err) {
        if (err) {
            throw err;
        }
    });
} 

在数据库处理跟发送send上采用了回调调用处理,经过严格测试完美通过。

原文引自:http://cnodejs.org/topic/52132b050a746c580b4f1716

回复 · 0

发表回复

你可以在回复中 @ 其他人