當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。