当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript multer.diskStorage函数代码示例

本文整理汇总了TypeScript中multer.diskStorage函数的典型用法代码示例。如果您正苦于以下问题:TypeScript diskStorage函数的具体用法?TypeScript diskStorage怎么用?TypeScript diskStorage使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了diskStorage函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: require

/* tslint:disable */
let multer = require('multer');
let path = require('path');
let crypto = require('crypto');
/* tslint:enable */

// image upload
let storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, process.cwd() + '/dist/temp/uploads/');
    },
    filename: function (req, file, cb) {
        crypto.pseudoRandomBytes(16, function (err, raw) {
            if (err) {
                return cb(err);
            }
            cb(null, raw.toString('hex') + path.extname(file.originalname));
        });
    }
});

export = storage;
开发者ID:Uter1007,项目名称:sumobase.core,代码行数:22,代码来源:image.storage.middleware.ts

示例2: function

var storage = multer.diskStorage({
    destination: function (req, file, callback) {
        var documentID: string = ""
        for (var index = 0; index < req.rawHeaders.length; index++) {
            var element = req.rawHeaders[index];
            if (element == "Referer") {
                documentID = req.rawHeaders[index + 1].slice(req.rawHeaders[index + 1].length - 24, req.rawHeaders[index + 1].length);
            }
        }
		var documentDir = './public/uploads/document/'; 

        var documentIdDir = './public/uploads/document/' + documentID.trim()// '/photos'
        var photoDirForDocId = documentIdDir + '/photos'
		console.log("Testing: "+documentIdDir);
		
		if (!fs.existsSync(documentDir)) {
            fs.mkdirSync(documentDir);            
        }
		
        if (!fs.existsSync(documentIdDir)) {
            fs.mkdirSync(documentIdDir);
            fs.mkdirSync(photoDirForDocId);
        }
        callback(null, photoDirForDocId);
    },
    filename: function (req, file, callback) {
        var originalName: string = ""
        for (var index = 0; index < req.rawHeaders.length; index++) {
            var element = req.rawHeaders[index];
            if (element == "originalName") {
                originalName = req.rawHeaders[index + 1];
                // replace all whitespace with nothing
                originalName = originalName.replace(/\s/g, "");
            }
        }
        callback(null, originalName);
    }
});
开发者ID:zalox,项目名称:Texd,代码行数:38,代码来源:upload.ts

示例3: multer

// MONGO CONFIG
const MongoClient = mongodb.MongoClient;
const ObjectId = mongodb.ObjectID;
const dbUrl = (config.dbUser && config.dbPwd) ? ('mongodb://' + config.dbUser + ':' + config.dbPwd + '@' + config.dbUrl) : ('mongodb://' + config.dbUrl);

// BCRYPT CONFIG
const saltRounds:number = 8;

// MULTER CONFIG
// AVATARS
const avtrUpload = multer({
  storage: multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, config.avtrPath)
    },
    filename: (req, file, cb) => {
      let ext = path.extname(file.originalname);
      cb(null, `${Math.random().toString(36).substring(7)}${ext}`);
    }
  })
});
// IMAGES
const imgUpload = multer({
  storage: multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, config.imgPath)
    },
    filename: (req, file, cb) => {
      let ext = path.extname(file.originalname);
      cb(null, `${Math.random().toString(36).substring(7)}${ext}`);
    }
开发者ID:Qcza,项目名称:mean-ng2-scaffold,代码行数:31,代码来源:server.ts

示例4: cb

    fileFilter: (req, file, cb) => {
        cb(null, true);
    }
});

const app = express();

app.post('/profile', upload.single('avatar'), (req: express.Request, res: express.Response, next: express.NextFunction) => {
});

app.post('/photos/upload', upload.array('photos', 12), (req: express.Request, res: express.Response, next: express.NextFunction) => {
});

const cpUpload = upload.fields([{ name: 'avatar', maxCount: 1 }, { name: 'gallery', maxCount: 8 }]);
app.post('/cool-profile', cpUpload, (req: express.Request, res: express.Response, next: express.NextFunction) => {
});

const diskStorage = multer.diskStorage({
    destination(req, file, cb) {
        cb(null, '/tmp/my-uploads');
    },
    filename(req, file, cb) {
        cb(null, file.fieldname + '-' + Date.now());
    }
});

const diskUpload = multer({ storage: diskStorage });

const memoryStorage = multer.memoryStorage();
const memoryUpload = multer({ storage: memoryStorage });
开发者ID:Crevil,项目名称:DefinitelyTyped,代码行数:30,代码来源:multer-tests.ts

示例5: require

import express = require('express');
import mongoose = require('mongoose');
import bodyParser = require('body-parser');
import http = require('http');
import path = require('path');
import User = require('./app/models/user.model');
var config  = require('./config/config');
var cors = require('cors');
import sio = require("socket.io");

//Upload-Modul Konfiguration
var multer  = require('multer');
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/'+req.body.pfad)
  },
  filename: function (req, file, cb) {
    cb(null, req.body.name)
  }
})
var upload = multer({ storage: storage });


//Logo laden aus Hauptordner
var favicon = require('serve-favicon');

//Mail Client
var nodemailer = require('nodemailer');
var smtpConfig = {
    host: 'smtp.strato.de',
    port: 465,
    secure: true, // use SSL
开发者ID:SocialMovieNetwork,项目名称:SMP-Finaler,代码行数:32,代码来源:server.ts

示例6: next

router.use(function(req, res, next) {
    // do logging
    console.log('Something is happening here.');
    next(); // make sure we go to the next routes and don't stop here
});
router.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
  next();
});

/* POST image to be OCRed. */
var storageDisk = multer.diskStorage({
  destination: 'uploads',
  filename: function (req, file, callback) {
    callback(null, Date.now() + '.' + file.originalname)
  }
})
var storageMem = multer.memoryStorage();
var uploadImage = multer({ storage: storageMem, limits: {fileSize: 1000000, files:1}, }).single('imageFile');
router.post('/ocrFile/', function(req, res) {
    uploadImage(req, res, function (err) {
        if (err) {
            // An error occurred when uploading
            console.log(err);
            return
        }
    // Everything is fine
        let recognitionResult = SudokuRendererServer.renderBoardImage(req.file, req, res);
  })
})
开发者ID:EnricoPicci,项目名称:Sudoku-on-Angular2,代码行数:32,代码来源:sudoku.ts

示例7: storage

 static storage(path: string[]) {
   return diskStorage({
     destination: (req, file, cb) => cb(null, join('.', ...path)),
     filename: (req, file, cb) => cb(null, `${v4().replace(/-/g, '')}${extname(file.originalname)}`),
   });
 }
开发者ID:mbechev,项目名称:Feedback,代码行数:6,代码来源:file.service.ts

示例8: async

export default async (bp: typeof sdk, db: Database) => {
  const diskStorage = multer.diskStorage({
    limits: {
      files: 1,
      fileSize: 5242880 // 5MB
    },
    filename: function(req, file, cb) {
      const userId = _.get(req, 'params.userId') || 'anonymous'
      const ext = path.extname(file.originalname)

      cb(undefined, `${userId}_${new Date().getTime()}${ext}`)
    }
  })

  const globalConfig = await bp.config.getModuleConfig('channel-web')

  let upload = multer({ storage: diskStorage })

  if (globalConfig.uploadsUseS3) {
    /*
      You can override AWS's default settings here. Example:
      { region: 'us-east-1', apiVersion: '2014-10-01', credentials: {...} }
     */
    const awsConfig = {
      region: globalConfig.uploadsS3Region,
      credentials: {
        accessKeyId: globalConfig.uploadsS3AWSAccessKey,
        secretAccessKey: globalConfig.uploadsS3AWSAccessSecret
      }
    }

    if (!awsConfig.credentials.accessKeyId && !awsConfig.credentials.secretAccessKey) {
      delete awsConfig.credentials
    }

    if (!awsConfig.region) {
      delete awsConfig.region
    }

    const s3 = new aws.S3(awsConfig)
    const s3Storage = multers3({
      s3: s3,
      bucket: globalConfig.uploadsS3Bucket || 'uploads',
      contentType: multers3.AUTO_CONTENT_TYPE,
      cacheControl: 'max-age=31536000', // one year caching
      acl: 'public-read',
      key: function(req, file, cb) {
        const userId = _.get(req, 'params.userId') || 'anonymous'
        const ext = path.extname(file.originalname)

        cb(undefined, `${userId}_${new Date().getTime()}${ext}`)
      }
    })

    upload = multer({ storage: s3Storage })
  }

  const router = bp.http.createRouterForBot('channel-web', { checkAuthentication: false, enableJsonBodyParser: true })

  const asyncApi = fn => async (req, res, next) => {
    try {
      await fn(req, res, next)
    } catch (err) {
      bp.logger.attachError(err).error('HTTP Handling Error')
      res.status(500).send(err && err.message)
    }
  }

  // ?conversationId=xxx (optional)
  router.post(
    '/messages/:userId',
    asyncApi(async (req, res) => {
      const { botId, userId = undefined } = req.params

      if (!validateUserId(userId)) {
        return res.status(400).send(ERR_USER_ID_REQ)
      }

      await bp.users.getOrCreateUser('web', userId) // Create the user if it doesn't exist

      const payload = req.body || {}
      let { conversationId = undefined } = req.query || {}
      conversationId = conversationId && parseInt(conversationId)

      if (!_.includes(['text', 'quick_reply', 'form', 'login_prompt', 'visit'], payload.type)) {
        // TODO: Support files
        return res.status(400).send(ERR_MSG_TYPE)
      }

      if (!conversationId) {
        conversationId = await db.getOrCreateRecentConversation(botId, userId, { originatesFromUserMessage: true })
      }

      await sendNewMessage(botId, userId, conversationId, payload)

      return res.sendStatus(200)
    })
  )

  // ?conversationId=xxx (required)
//.........这里部分代码省略.........
开发者ID:seffalabdelaziz,项目名称:botpress,代码行数:101,代码来源:api.ts

示例9: filename

import * as multer from "multer"

const storage = multer.diskStorage({
  // 设置上传文件路径,以后可以扩展成上传至七牛,文件服务器等等
  // Note:如果你传递的是一个函数,你负责创建文件夹,如果你传递的是一个字符串,multer会自动创建
  destination: process.cwd() + "/public/upload",
  // TODO:文件区分目录存放
  // 获取文件MD5,重命名,添加后缀,文件重复会直接覆盖
  filename(req, file, cb) {
    const fileFormat = file.originalname.split(".")
    cb(
      null,
      file.fieldname +
        "-" +
        Date.now() +
        "." +
        fileFormat[fileFormat.length - 1]
    )
  }
})

// 添加配置文件到muler对象。
export const upload = multer({
  storage
})
开发者ID:yanhao1991,项目名称:shift-server,代码行数:25,代码来源:file-upload.ts

示例10: require

var xlsx = require('node-xlsx');
var multer = require('multer');

var uploadPath = 'upload/';

// read excel file content
export let read = (filename): string => {
    var file = xlsx.parse(uploadPath + filename);
    var sheet = file[0].data;
    var html = '';
    html = JSON.stringify(sheet);
    return html;
}

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, uploadPath);
    },
    filename: function (req, file, cb) {
        cb(null, Date.now() + '-' + file.originalname);
    }
});
// upload file to specific folder
export let upload = multer({ storage: storage });
开发者ID:lurenja,项目名称:wab,代码行数:24,代码来源:excel-handler.ts


注:本文中的multer.diskStorage函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。