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


TypeScript multer.memoryStorage函数代码示例

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


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

示例1: getBodyParser

function getBodyParser(config: JsonBodyOptions | FileBodyOptions): RequestHandler {
    if (!config) return DEFAULT_JSON_PARSER;

    if (config.type === 'json') {
        return bodyParser.json(config);
    }
    else if (config.type == 'files') {
        const fConfig = config as FileBodyOptions;

        // validate config object
        if (typeof fConfig.field !== 'string') throw new TypeError(`'field' is undefined in file body options`);
        if (!fConfig.limits) throw new TypeError(`'limits' are undefined in file body options`);
        if (typeof fConfig.limits.size !== 'number' || typeof fConfig.limits.count !== 'number')
            throw new TypeError(`'limits' are invalid in file body options`);

        // build middleware
        const uploader = multer({
            storage: fConfig.storage || multer.memoryStorage(),
            limits: {
                files   : fConfig.limits.count,
                fileSize: fConfig.limits.size
            }
        }).array(fConfig.field);

        return function(request, response, next) {
            uploader(request, response, function (error) {
                if (error) {
                    const code: string = (error as any).code;
                    if (typeof code === 'string' && code.startsWith('LIMIT')) {
                        error = new Exception({ message: 'Upload failed', cause: error, status: HttpStatusCode.InvalidInputs });
                    }
                }
                next(error);
            });
        };
    }
    else if (config.type === 'multipart') {
        const bConfig = config as MultipartBodyOptions;

        const uploader = multer({
            storage : bConfig.storage || multer.memoryStorage(),
            limits  : bConfig.limits
        }).any();

        return function(request, response, next) {
            uploader(request, response, function (error) {
                if (error) {
                    const code: string = (error as any).code;
                    if (typeof code === 'string' && code.startsWith('LIMIT')) {
                        error = new Exception({ message: 'Request failed', cause: error, status: HttpStatusCode.InvalidInputs });
                    }
                }
                next(error);
            });
        };
    }
    else {
        throw new TypeError(`Body type '${config.type}' is not supported`);
    }
}
开发者ID:herculesinc,项目名称:nova-server,代码行数:60,代码来源:RouteController.ts

示例2: paramUploadOptions

function paramUploadOptions(options){
  options = options || {}
  options.storage = options.storage || multer.memoryStorage()
  options.putSingleFilesInArray = options.putSingleFilesInArray===null ? true : options.putSingleFilesInArray
}
开发者ID:AckerApple,项目名称:ack-node,代码行数:5,代码来源:router.ts

示例3: 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:AbraaoAlves,项目名称:DefinitelyTyped,代码行数:30,代码来源:multer-tests.ts

示例4: require

var request = require('request');

var http = require('http');
var https = require('https');
var fs = require('fs');

var express = require('express');
var router = express.Router();
var User =  userModel.repository;
var Comic =  comicModel.repository;
var Page =  pageModel.repository;
var Avatar =  avatarModel.repository;
var jwt = require('jsonwebtoken');
var multer  = require('multer');
var upload = multer({storage : multer.memoryStorage()});
var mongoose = require('mongoose');
var base64 = require('node-base64-image');

/* GET home page. */
router.get('/', accessController.renderIndex);

/* GET profile page. */
router.get('/myprofile', accessController.renderMyprofile);


/* GET someone elses profile page */
router.route('/aprofile/:user_id')
	.get(function(req, res) {
		var isloggedin = false;
		var subd = false;
开发者ID:ffanzhang,项目名称:CheweyComicsContinued,代码行数:30,代码来源:index.ts

示例5: it

    it('allows for pre-parsed POST bodies', () => {
      // Note: this is not the only way to handle file uploads with GraphQL,
      // but it is terse and illustrative of using express-graphql and multer
      // together.

      // A simple schema which includes a mutation.
      const UploadedFileType = new GraphQLObjectType({
        name: 'UploadedFile',
        fields: {
          originalname: { type: GraphQLString },
          mimetype: { type: GraphQLString }
        }
      });

      const TestMutationSchema = new GraphQLSchema({
        query: new GraphQLObjectType({
          name: 'QueryRoot',
          fields: {
            test: { type: GraphQLString }
          }
        }),
        mutation: new GraphQLObjectType({
          name: 'MutationRoot',
          fields: {
            uploadFile: {
              type: UploadedFileType,
              resolve(rootValue) {
                // For this test demo, we're just returning the uploaded
                // file directly, but presumably you might return a Promise
                // to go store the file somewhere first.
                return rootValue.request.file;
              }
            }
          }
        })
      });

      const app = express();

      // Multer provides multipart form data parsing.
      const storage = multer.memoryStorage();
      app.use('/graphql', multer({ storage }).single('file'));

      // Providing the request as part of `rootValue` allows it to
      // be accessible from within Schema resolve functions.
      app.use('/graphql', graphqlExpress(req => {
        return {
          schema: TestMutationSchema,
          rootValue: { request: req }
        };
      }));

      const req = request(app)
        .post('/graphql')
        .field('query', `mutation TestMutation {
          uploadFile { originalname, mimetype }
        }`)
        .attach('file', __filename);

      return req.then((response) => {
        expect(JSON.parse(response.text)).to.deep.equal({
          data: {
            uploadFile: {
              originalname: 'apolloServerHttp.test.js',
              mimetype: 'application/javascript'
            }
          }
        });
      });
    });
开发者ID:convoyinc,项目名称:apollo-server,代码行数:70,代码来源:apolloServerHttp.test.ts

示例6: next

});
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);
  })
})

/*
 * GET one random message for the nasty player
开发者ID:EnricoPicci,项目名称:Sudoku-on-Angular2,代码行数:31,代码来源:sudoku.ts

示例7: require

/// <reference path="../../../typings/main.d.ts" />

import {Router} from "express";
"use strict";

var User = require('../model/user-model');
import {UserController} from '../controller/user-controller';
import {AuthService} from "../../../auth/service/auth-service";
var express = require('express');
var multer = require('multer')
var fs = require('fs')
var storage = multer.memoryStorage()
var upload = multer({storage: storage})

export class UserRoutes {

    static init():Router {
        var router = express.Router();

        router
            .route('/overall')
            .get(UserController.overall);

        router
            .route('/cleanup')
            .post(UserController.cleanup);

        router
            .route('/overall/hired')
            .get(UserController.hired);
开发者ID:suvetig,项目名称:ppt,代码行数:30,代码来源:user-routes.ts

示例8: require

//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import {gapis, config, logging, app} from '../../app'; 
import {Util} from './utils';
var path = require('path');
var request = require('request');
var Multer = require('multer');
export const MAX_ALLOWED_UPLOAD_SIZE = 20 * 1024 * 1024;
export const USER_UPLOADS_FOLDER = 'user-uploads';
var storage = Multer.memoryStorage();
var _ = require('lodash');
var util = require('util');
var fs = require('fs');
var mkdirp = require('mkdirp');
export var multer = Multer({
    storage: storage,
    limits: { fileSize: MAX_ALLOWED_UPLOAD_SIZE, files: 20 }
});
export const TEMP_UPLOAD_PATH = 'tmp/upload/';
export class Uploader {

    // Multer handles parsing multipart/form-data requests.
    // This instance is configured to store images in memory and re-name to avoid
    // conflicting with existing objects. This makes it straightforward to upload
    // to Cloud Storage.
开发者ID:zaksie,项目名称:gotouch,代码行数:31,代码来源:uploader.ts

示例9: Copyright

/*
	Flowerbox
	Copyright (C) 2016 Kayateia
	For license info, please see notes/gpl-3.0.txt under the project root.
*/

import * as multer from "multer";

let storage = multer.memoryStorage();

// var upload = multer({ storage: storage }).single("userPhoto");
let uploader:any = multer({ storage: storage }).any();

// Returns a Promise that will handle turning a multi-part form body into a proper req.body.
export function upload(req, res) {
	return new Promise<any>(function(resolve, reject) {
		uploader(req, res, function(err) {
			if (err)
				reject(err);
			else
				resolve();
		});
	});
}
开发者ID:kayateia,项目名称:flowerbox-server,代码行数:24,代码来源:Multer.ts


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