AngualrJs 最新 文件图片上传教程7:Server-controllers

womeninformationmanagement.server.controller.js

'use strict';

/**
 * Module dependencies
 */
var _ = require('lodash'),
  fs = require('fs'),
  path = require('path'),
  config = require(path.resolve('./config/config')),
  multer = require(path.resolve('./config/private/multer')),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
  sequelize = require(path.resolve('./config/lib/sequelize')),
  logger = require(path.resolve('./config/lib/logger'))
    .getLogger_FileNameBase(__filename);

//创建接收头像对象
var uploadImage = new multer('womenfile',
  4 * 1024 * 1024,
  /image/, '.doc');
//创建目录
uploadImage.mkPaths();

/**
 * Create an womenInformationManagement
 */
exports.create = function (req, res) {
  var WomenInformationManagement = sequelize.model('WomenInformationManagement');
  var womenInformationManagement = WomenInformationManagement.build(req.body);
  var newingImageUrl;
  var newingPhoto1ImageUrl;
  if (womenInformationManagement) {
    uploadImage.recv(req, res, [{name: 'file_path'}, {name: 'photo'}])
      .then(updateUserInfo)
      .then(function () {
        res.json(womenInformationManagement);
      })
      .catch(function (err) {
        logger.error('上传文件失败:', err);
        res.status(422).send(err);
      });
  } else {
    res.status(401).send({
      message: 'womenInformationManagement is not exist'
    });
  }
  function updateUserInfo(files) {
    return new Promise(function (resolve, reject) {
      if (womenInformationManagement) {
        if (files && files.file_path && files.file_path.length === 1) {
          womenInformationManagement.file_path = path.join(uploadImage.mountDir, files.file_path[0].filename).replace(/\\/g, '/');
          newingImageUrl = womenInformationManagement.file_path;
        }
        if (files && files.photo && files.photo.length === 1) {
          womenInformationManagement.photo = path.join(uploadImage.mountDir, files.photo[0].filename).replace(/\\/g, '/');
          newingPhoto1ImageUrl = womenInformationManagement.photo;
        }
        womenInformationManagement.title = req.body.title;
        womenInformationManagement.type = req.body.type;
        // womenInformationManagement.file_content = req.body.file_content;
        womenInformationManagement.time_update = req.body.time_update;
        // womenInformationManagement.photo = req.body.photo;
        womenInformationManagement.remark = req.body.remark;
        //图片
        womenInformationManagement.save().then(function () {
          resolve();
        }).catch(function (err) {
          reject(err);
        });
      } else {
        reject(new Error('no upload'));
      }
    });
  }
};

/**
 * Show the current womenInformationManagement
 */
exports.read = function (req, res) {
  var womenInformationManagement = req.model ? req.model.toJSON() : {};
  womenInformationManagement.isCurrentUserOwner = !!(req.user && womenInformationManagement.user && womenInformationManagement.user.id.toString() === req.user.id.toString());

  res.json(womenInformationManagement);
};

/**
 * Update an womenInformationManagement
 */
exports.update = function (req, res) {
  var womenInformationManagement = req.model;
  var newingFileUrl;
  var existingFileUrl;
  var newingPhotoImageUrl;
  var existingPhotoImageUrl;
  if (womenInformationManagement) {
    existingFileUrl = womenInformationManagement.file_path;
    existingPhotoImageUrl = womenInformationManagement.photo;
    uploadImage.recv(req, res, [{name: 'file_path'}, {name: 'photo'}])
      .then(updateUserInfo)
      .then(deleteOldImage)
      .then(function () {
        res.json(womenInformationManagement);
      })
      .catch(function (err) {
        logger.error('recv upload womenInformationManagement file err:', err);
        res.status(422).send(err);
      });
  } else {
    res.status(401).send({
      message: 'womenInformationManagement is not exist'
    });
  }

  function updateUserInfo(files) {
    return new Promise(function (resolve, reject) {
      if (womenInformationManagement) {
        if (files && files.file_path && files.file_path.length === 1) {
          womenInformationManagement.file_path = path.join(uploadImage.mountDir, files.file_path[0].filename).replace(/\\/g, '/');
          newingFileUrl = womenInformationManagement.file_path;
        }
        if (files && files.photo && files.photo.length === 1) {
          womenInformationManagement.photo = path.join(uploadImage.mountDir, files.photo[0].filename).replace(/\\/g, '/');
          newingPhotoImageUrl = womenInformationManagement.photo;
        }
        womenInformationManagement.title = req.body.title;
        womenInformationManagement.type = req.body.type;
        // womenInformationManagement.file_content = req.body.file_content;
        womenInformationManagement.time_update = req.body.time_update;
        // womenInformationManagement.photo = req.body.photo;
        womenInformationManagement.remark = req.body.remark;
        //图片
        womenInformationManagement.save().then(function () {
          resolve();
        }).catch(function (err) {
          reject(err);
        });
      } else {
        reject(new Error('no upload'));
      }
    });
  }
  //删除旧照片
  function deleteOldImage() {
    return new Promise(function (resolve, reject) {
      if (existingPhotoImageUrl && newingPhotoImageUrl) {
        var oldimgname = existingPhotoImageUrl.replace(uploadImage.mountDir, uploadImage.diskDir);
        fs.unlink(oldimgname, function (unlinkError) {
          if (unlinkError) {
            resolve();
          } else {
            resolve();
          }
        });
      } else {
        resolve();
      }
      if (existingFileUrl && newingFileUrl) {
        var oldfile = existingFileUrl.replace(uploadImage.mountDir, uploadImage.diskDir);
        fs.unlink(oldfile, function (unlinkError) {
          if (unlinkError) {
            resolve();
          } else {
            resolve();
          }
        });
      } else {
        resolve();
      }
    });
  }
};

/**
 * Delete an womenInformationManagement
 */
exports.delete = function (req, res) {
  var womenInformationManagement = req.model;

  womenInformationManagement.destroy().then(function () {
    res.json(womenInformationManagement);
  }).catch(function (err) {
    return res.status(422).send({
      message: errorHandler.getErrorMessage(err)
    });
  });
};

/**
 * List of WomenInformationManagement
 */
exports.list = function (req, res) {
  var WomenInformationManagement = sequelize.model('WomenInformationManagement');

  WomenInformationManagement.findAll({
    limit: [0, 20],
    order: 'id ASC'
  }).then(function (womenInformationManagement) {
    return res.jsonp(womenInformationManagement);
  }).catch(function (err) {
    logger.error('womenInformationManagement list error:', err);
    return res.status(422).send(err);
  });
};

//----分页
function listByPage(req, res, limit, offset) {
  var WomenInformationManagement = sequelize.model('WomenInformationManagement');
  WomenInformationManagement.findAll({
    limit: [limit, offset],
    order: 'id ASC'
  }).then(function (commMemberTable) {
    return res.jsonp(commMemberTable);
  }).catch(function (err) {
    logger.error('WomenInformationManagement list error:', err);
    return res.status(422).send(err);
  });
}
//---------总数
function listCount(req, res) {
  var sql = 'select count(*) sum from WomenInformationManagement';
  sequelize.query(sql, {type: sequelize.QueryTypes.SELECT}).then(function (infos) {
    res.jsonp(infos);
  }).catch(function (err) {
    logger.error('listCount error:', err);
    return res.status(422).send(err);
  });
}

/**
 * WomenInformationManagement middleware
 */
exports.womenInformationManagementByID = function (req, res, next, id) {
  var WomenInformationManagement = sequelize.model('WomenInformationManagement');
  var limit = parseInt(req.query.limit, 0);//(pageNum-1)*20
  var offset = parseInt(req.query.offset, 0);//20 每页总数
  if (offset !== 0 && id === '0') {
    listByPage(req, res, limit, offset);
  } else if (limit === 0 && offset === 0 && id === '0') {
    listCount(req, res);
  } else if (id !== '0') {
    WomenInformationManagement.findOne({
      where: {id: id}
    }).then(function (womenInformationManagement) {
      if (!womenInformationManagement) {
        logger.error('No womenInformationManagement with that identifier has been found');
        return res.status(404).send({
          message: 'No womenInformationManagement with that identifier has been found'
        });
      }

      req.model = womenInformationManagement;
      next();
    }).catch(function (err) {
      //return next(err);
      logger.error('womenInformationManagement ByID error:', err);
      res.status(422).send({
        message: errorHandler.getErrorMessage(err)
      });
    });
  }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值