4.7 multer文件上传-博客后端Api-NodeJs+Express+Mysql实战

in 编程
关注公众号【好便宜】( ID:haopianyi222 ),领红包啦~
阿里云,国内最大的云服务商,注册就送数千元优惠券:https://t.cn/AiQe5A0g
腾讯云,良心云,价格优惠: https://t.cn/AieHwwKl
搬瓦工,CN2 GIA 优质线路,搭梯子、海外建站推荐: https://t.cn/AieHwfX9
multer文件上传
https://github.com/expressjs/...

在博客系统中会涉及到文件上传,这时候需要用到 multer文件上传

model层

/**
 * Attachment附件表
 * @type {[type]}
 */
var Sequelize = require('sequelize');
var Mysql = require('./mysql');

var Attachment = Mysql.define('attachment', {
    uuid: {
        type: Sequelize.UUID,
        allowNull: false,
        primaryKey: true,
        defaultValue: Sequelize.UUIDV1,//Sequelize.UUIDV4
    }, //uuid
    name: Sequelize.STRING, //附件名字
    relativeUrl: Sequelize.STRING, //附件相对地址
    absoluteUrl: Sequelize.STRING, //附件绝对地址
    type: Sequelize.STRING(2), //附件类型(1图片、2视频、3音频、4其他文件)
}, {
    freezeTableName: true, // 自定义表名
    tableName: 'Attachment',
    timestamps: true, // 添加时间戳属性 (updatedAt, createdAt)
    createdAt: 'createDate',// 将createdAt字段改个名
    updatedAt: 'updateDate',// 将updatedAt字段改个名
    indexes: [{ // 索引
        type: 'UNIQUE',
        method: 'BTREE',
        unique: true, //唯一
        fields: ['uuid'],
    }],
});

module.exports = Attachment;

config层 系统配置

clipboard.png

router层

clipboard.png

service层

/**
 * 文件服务
 * add by wwj
 * 2019-05-04 12:03:39
 */
var fs = require('fs');
var path = require('path'); //路径
var uuid = require('node-uuid'); //uuid
var Promise = require("bluebird");
var multer = require('multer'); //文件上传
var config = require('config-lite'); //配置

module.exports = {
    /**
     * 获取年月
     */
    getYearMonth: function() {
        var fdate = new Date();
        return fdate.getFullYear() + '' + (fdate.getMonth() + 1) + '' + fdate.getDate();
    },
    /**
     * 连接文件存放路径
     * type文件对应类型 比如文章对应article
     * filename 文件名含后缀名
     */
    createFilePath: function(pathType, filename) {
        var that = this;
        var fpath = path.join(__dirname, '../public/attchments', (pathType || 'default'), that.getYearMonth());
        if (!fs.existsSync(fpath)) {
            fs.mkdirSync(fpath);
        }
        if (filename) {
            return fpath + '/' + filename;
        } else {
            return fpath;
        }
    },
    /**
     * 处理文件上传
     */
    setFileUpload: function(opts) {
        var that = this;
        var storage = multer.diskStorage({
            //设置上传后文件路径,uploads文件夹会自动创建。
            destination: function(req, file, cb) {
                cb(null, that.createFilePath(opts.pathType))
            },
            //给上传文件重命名,获取添加后缀名
            filename: function(req, file, cb) {
                var fileFormat = file.originalname.split(".");
                // cb(null, file.originalname + '_' + Math.ceil(Math.random()*9) + Date.now() + "." + fileFormat[fileFormat.length - 1]);
                cb(null, uuid() + "." + fileFormat[fileFormat.length - 1]);
            },
        });
        var upload = multer({
            limits: {
                fileSize: config.file.limit.fileSize[opts.pathType] || config.file.limit.fileSize.default, //允许最大
            },
            storage: storage,
        });
        return upload;
    }
}

controller层文件上传

/**
 * common controllers
 * add by wwj
 * 2016-12-22 17:45:53
 */
var co = require('co');
var Promise = require("bluebird");
var i18n = require('i18n'); //国际化
var utils = require('../libs/utils'); //工具类
var Attachment = require('../models/index').Attachment; //房源附件
var fileService = require('../services/file'); //文件服务

module.exports = {
  /**
   * 文件上传
   */
  uploadEnclosure: function(req, res, next) {
    //文件s
    var files = req.files;
    if (!files || !files.length) {
      //err
      utils.handleError({
        response: res,
        error: i18n.__('uploadFileFail'),
      });
      return;
    }
    co(function*() {
      //all
      var fileResult = yield Promise.all(files.map(function(file) {
        return Attachment.create({
          name: file.originalname, //文件名
          relativeUrl: file.filename, //相对路径
          absoluteUrl: fileService.getFilePath("default", file.filename),
          type: fileService.handlerFileType(file.mimetype), //对应int值
          size: file.size, //文件大小
        });
      }));
      //success
      utils.handleJson({
        response: res,
        msg: i18n.__('uploadFileSuccess'),
        result: {
          fileList: fileResult,
        },
      });
    }).catch(function(error) {
      //err
      utils.handleError({
        response: res,
        error: error,
      });
    });
  },
};

后面写到前端的时候再说 怎么ajax fileupload调用

关注公众号【好便宜】( ID:haopianyi222 ),领红包啦~
阿里云,国内最大的云服务商,注册就送数千元优惠券:https://t.cn/AiQe5A0g
腾讯云,良心云,价格优惠: https://t.cn/AieHwwKl
搬瓦工,CN2 GIA 优质线路,搭梯子、海外建站推荐: https://t.cn/AieHwfX9
扫一扫关注公众号添加购物返利助手,领红包
Comments are closed.

推荐使用阿里云服务器

超多优惠券

服务器最低一折,一年不到100!

朕已阅去看看