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