本文整理汇总了TypeScript中multer.default方法的典型用法代码示例。如果您正苦于以下问题:TypeScript multer.default方法的具体用法?TypeScript multer.default怎么用?TypeScript multer.default使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类multer
的用法示例。
在下文中一共展示了multer.default方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: multer
endpoints.forEach(endpoint =>
endpoint.withFile ?
app.post('/' + endpoint.name,
endpoint.withFile ? multer({ dest: 'uploads/' }).single('file') : null,
require('./api-handler').default.bind(null, endpoint)) :
app.post('/' + endpoint.name,
require('./api-handler').default.bind(null, endpoint))
示例2: 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`);
}
}
示例3: start
start() {
let app: express.Express = express();
app.use('/', express.static('public'));
var upload: multer.Instance = multer(); // for parsing multipart/form-data
//Server Middlewares configuration part
app.use(allowCrossDomain);
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(expressSession({secret: 'swcmi'}));
//To use passport
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
//start router
this.apiRouter.init(app);
//port
app.listen(10000, function () {
console.log('SuWon church API Server listening on port 10000!')
});
}
示例4: registerParsers
private registerParsers() {
// configure app to use bodyParser()
// this will let us get the data from a POST
this.app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
this.app.use(bodyParser.json()); // for parsing application/json
this.app.use(multer().any()); // for parsing multipart/form-data
}
示例5: createReqFiles
function createReqFiles (
fieldNames: string[],
mimeTypes: { [ id: string ]: string },
destinations: { [ fieldName: string ]: string }
) {
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, destinations[file.fieldname])
},
filename: async (req, file, cb) => {
const extension = mimeTypes[file.mimetype]
let randomString = ''
try {
randomString = await generateRandomString(16)
} catch (err) {
logger.error('Cannot generate random string for file name.', err)
randomString = 'fake-random-string'
}
cb(null, randomString + extension)
}
})
const fields = []
for (const fieldName of fieldNames) {
fields.push({
name: fieldName,
maxCount: 1
})
}
return multer({ storage }).fields(fields)
}
示例6: function
describe("Laod simple service rest", function() {
let app = express();
app.use(bodyParser.urlencoded({extended : false}));
app.use(multer().array());
ServiceLoader.loadService(app, new serviceTest());
it("should return a get", function(done) {
request(app)
.get("/one/1")
.expect('{"id":"1","method":"get"}', done);
});
it("should return a post", function(done) {
request(app)
.post("/one")
.field("id", 11)
.expect('{"id":"11","method":"post"}', done);
});
it("should return a delete", function(done) {
request(app)
.delete("/one/2")
.expect('{"id":"2","method":"delete"}', done);
});
it("should return a put", function(done) {
request(app)
.put("/one/3")
.expect('{"id":"3","method":"put"}', done);
});
it("should return a patch", function(done) {
request(app)
.patch("/one/4")
.expect('{"id":"4","method":"patch"}', done);
});
});
示例7: multer
/// <reference path="tsd.d.ts" />
import * as express from 'express'
import * as multer from 'multer'
import * as path from 'path';
import * as fs from 'fs';
import * as db from 'db';
import * as bodyParser from 'body-parser'
import {config} from 'config';
import {api as dapi} from 'discourse'
var upload = multer({ dest: config.uploadPath })
var app = express()
app.use(bodyParser.urlencoded({ extended: false }))
app.use(express.static('public'));
app.post('/postImg', upload.single('img'), function (req, res, next) {
var tmpFile = path.join(__dirname, req.file.path);
fs.rename(tmpFile, tmpFile + '.jpg', function () {
res.json({ url: config.webAccessUploadURI + req.file.filename + '.jpg' });
})
})
app.post('/post', function (req, res, next) {
console.log(req.body);
var doc = req.body;
db.posts.loadDatabase();
db.posts.insert(doc, function (err, newDoc) { // Callback is optional
if (err) {
示例8: Image
not_submitted: responses[1]
});
});
});
});
});
});
const upload = multer({
limits: {
fileSize: 1000000
},
storage: multerS3({
acl: "public-read",
bucket: "famjam",
contentType: (req, file, cb) => {
cb(null, "image/jpeg");
},
key: (req, file, cb) => {
cb(null, uuid.v4());
},
s3: s3
})
});
api.post("/topics/:id", authorizeToken, upload.single("photo"), (req, res) => {
new Image({
_creator: (req.authenticatedUser as IUser)._id,
_topic: req.params["id"],
description: req.body["description"],
url: (req.file as any).location
}).save((err, image: IImage) => {
示例9: express
import * as express from 'express'
import * as bodyParser from 'body-parser'
import * as multer from 'multer'
import * as path from 'path'
import route from '../route'
import reqRoute from './reqRoute'
const port: number = 8989
const app: any = express()
const upload: any = multer()
const server = app.listen(port, ():void=> {
console.log(`http://localhost:${port}`)
})
const filePath = (fileName: string): string => {
return path.join(__dirname + '/../data/' + fileName)
}
app.use(bodyParser.json({ limit: '50mb' }))
app.use(bodyParser.urlencoded({ extended: true }))
app.use(express.static('./dist'))
app.get('*', async (req: any,res: any) => {
let data: any = await route(req)
if( data.type === 'data'){
res.send(data.data)
} else {
res.sendFile(filePath(await reqRoute(req.path)))
// res.sendFile(filePath(data))
示例10: 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}`);
}