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


TypeScript busboy.on函数代码示例

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


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

示例1: serverFn

function serverFn(req: http.ServerRequest, res: http.ServerResponse) {
  if (req.method === 'POST') {
    var busboy = new Busboy({ headers: req.headers });
    busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
      console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
      file.on('data', function(data: Buffer) {
        console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
      });
      file.on('end', function() {
        console.log('File [' + fieldname + '] Finished');
      });
    });
    busboy.on('field', function(fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
      console.log('Field [' + fieldname + ']: value: ' + util.inspect(val));
    });
    busboy.on('finish', function() {
      console.log('Done parsing form!');
      res.writeHead(303, { Connection: 'close', Location: '/' });
      res.end();
    });
    req.pipe(busboy);
  } else if (req.method === 'GET') {
    res.writeHead(200, { Connection: 'close' });
    res.end('<html><head></head><body>\
               <form method="POST" enctype="multipart/form-data">\
                <input type="text" name="textfield"><br />\
                <input type="file" name="filefield"><br />\
                <input type="submit">\
              </form>\
            </body></html>');
  }
}
开发者ID:Agamnentzar,项目名称:DefinitelyTyped,代码行数:32,代码来源:busboy-tests.ts

示例2: Busboy

		return new Promise<FileDocument>((resolve, reject) => {
			let numFiles = 0;
			let internalErr: ApiError;
			let file: FileDocument;
			let finished = false;
			const busboy = new Busboy({ headers: ctx.request.headers });
			busboy.on('file', (fieldname, stream, filename) => {
				numFiles++;
				if (numFiles > 1) {
					internalErr = new ApiError('Multipart requests must only contain one file.').code('too_many_files').status(422);
					stream.resume();
					return;
				}
				logger.info(ctx.state, '[FileStorage.handleMultipartUpload] Starting file (multipart) upload of "%s"', filename);
				const fileData = {
					name: filename,
					bytes: 0,
					variations: {},
					created_at: new Date(),
					mime_type: ctx.query.content_type,
					file_type: ctx.query.type,
					_created_by: ctx.state.user._id,
				};
				FileUtil.create(ctx.state, fileData as FileDocument, stream)
					.then(f => {
						if (finished) {
							return resolve(f);
						}
						file = f;
					})
					.catch(e => {
						if (finished) {
							return reject(e);
						}
						internalErr = e;
					});
			});
			busboy.on('error', (busboyErr: any) => {
				logger.warn(ctx.state, '[FileApi.handleMultipartUpload] Error: %s', busboyErr);
				reject(busboyErr);
			});
			busboy.on('finish', () => {
				if (internalErr) {
					if (file) {
						logger.warn(ctx.state, '[FileApi.handleMultipartUpload] Removing %s', file.toShortString());
						file.remove().then(() => reject(internalErr));
					} else {
						return reject(internalErr);
					}
				}
				if (file) {
					return resolve(file);
				}
				finished = true;
			});
			ctx.req.pipe(busboy);
		});
开发者ID:freezy,项目名称:node-vpdb,代码行数:57,代码来源:file.storage.ts

示例3: parsePost

function parsePost(req, res, next) {
    if (req.method === 'POST') {
        var busboy = new Busboy({
            headers: req.headers,
            limits: {
                files: 1,
                fileSize: 10 * 1000 * 1000
            }
        });
        var tmpfiles = [];
        req.post = {};
        req.files = {};
        busboy.on('field', function (fieldname, val) {
            // php style array properties
            if (/\[\]$/.test(fieldname)) {
                var match = /(.+)\[\]$/.exec(fieldname);
                if (!(req.post[match[1]] instanceof Array))
                    req.post[match[1]] = [];
                req.post[match[1]].push(val);
            } else if (/\[.+\]$/.test(fieldname)) {
                var match = /(.+)\[(.+)\]/.exec(fieldname);
                if (!(req.post[match[1]] instanceof Object))
                    req.post[match[1]] = {};
                req.post[match[1]][match[2]] = val;
            } else {
                req.post[fieldname] = val;
            }
        });
        busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
            var tmpfile = path.join(os.tmpdir(), path.basename(filename));
            req.files[fieldname] = {tmpfile: tmpfile, filename: filename, mimetype: mimetype};
            tmpfiles.push(tmpfile);
            file.pipe(fs.createWriteStream(tmpfile));
        });
        busboy.on('finish', function () {
            next();
        });
        res.on('finish', function() {
            for (let file of tmpfiles) {
                debug('Cleaning up ' + file);
                fs.unlink(file);
            }
        });
        req.pipe(busboy);
    } else {
        next();
    }
}
开发者ID:notenoughneon,项目名称:skein,代码行数:48,代码来源:api.ts

示例4: defaultGetStorage

  return T.makeTask_(cb => {
    const options: MutterOptions = opts || {};
    const req = ctx.request;
    const fileFilter = options.fileFilter || defaultFileFilter;
    const limits = options.limits;
    const storage = options.getStorage ? options.getStorage(ctx) : defaultGetStorage(ctx);

    const params = Object.create(null);
    const files = Object.create(null);

    const busboy = new Busboy({ limits, headers: req.headers, preservePath: options.preservePath });
    const _stream = getContentStream(req, req.headers);
    const stream = isJust(_stream) ? _stream.value : req;
    const pendingWrites = new Counter();
    let isDone = false;
    let readFinished = false;
    let errorOccured = false;
    let uploadedFiles: FileInfo[] = [];

    function done(err?: Error | null) {
      if (isDone) return;
      isDone = true;
      stream.unpipe(busboy);
      drainStream(stream);
      busboy.removeAllListeners();
      onFinished(req, () => {
        if (err) return cb(err);

        cb(null, [params, files]);
      });
    }

    function indicateDone() {
      if (readFinished && pendingWrites.isZero() && !errorOccured) done();
    }

    function abortWithError(uploadError: Error) {
      if (errorOccured) return;
      errorOccured = true;
      pendingWrites.onceZero(() => {
        T.runTask(T.forInPar_(uploadedFiles, file => storage.removeFile(file)), (err) => {
          /* istanbul ignore if */
          if (err) return done(err);
          done(uploadError);
        });
      });
    }

    function abortWithCode(code: keyof (typeof errorMessages), optionalField?: string) {
      abortWithError(makeError(code, optionalField));
    }

    busboy.on('field', (fieldname, value, fieldnameTruncated, valueTruncated) => {
      if (fieldnameTruncated) return abortWithCode('LIMIT_FIELD_KEY');
      if (valueTruncated) return abortWithCode('LIMIT_FIELD_VALUE', fieldname);

      // Work around bug in Busboy (https://github.com/mscdex/busboy/issues/6)
      if (limits && limits.hasOwnProperty('fieldNameSize')) {
        if (fieldname.length > (limits as any).fieldNameSize) return abortWithCode('LIMIT_FIELD_KEY');
      }

      appendField(params, fieldname, value);
    });

    busboy.on('file', (fieldname, filestream, originalname, encoding, mimeType) => {
      if (!fieldname) return filestream.resume();

      // Work around bug in Busboy (https://github.com/mscdex/busboy/issues/6)
      if (limits && limits.hasOwnProperty('fieldNameSize')) {
        if (fieldname.length > (limits as any).fieldNameSize) return abortWithCode('LIMIT_FIELD_KEY');
      }

      const file: FileUpload = {
        fieldname,
        originalname,
        encoding,
        mimeType
      };
      const placeholder = insertPlaceholder(files, file);

      T.runTask(fileFilter(ctx, file), (err, includeFile) => {
        if (err) {
          removePlaceholder(files, placeholder);
          return abortWithError(err);
        }

        if (!includeFile) {
          removePlaceholder(files, placeholder);
          return filestream.resume();
        }

        let aborting = false;
        pendingWrites.increment();

        filestream.on('error', (err) => {
          pendingWrites.decrement();
          abortWithError(err);
        });

        filestream.on('limit', function () {
//.........这里部分代码省略.........
开发者ID:syaiful6,项目名称:jonggrang,代码行数:101,代码来源:parser.ts

示例5: processArgs

    fng.app.post.apply(fng.app, processArgs(modifiedOptions, ['file/upload/:model', function (req: any, res: any) {

        function uploadFile(gfs, file, options, callback) {
            let stream;
            if (callback == null) {
                callback = function() {};
            }
            let mongo = fng.mongoose.mongo;
            options._id = new mongo.ObjectID();
            options.mode = 'w';
            stream = gfs.createWriteStream(options);
            stream.on('close', function(metaData) {
                return callback(null, metaData);
            });
            stream.on('error', callback);
            return file.pipe(stream);
        }

        let model = req.params.model;
        let busboy = new Busboy({
            headers: req.headers
        });
        let mongo = fng.mongoose.mongo;
        let resource = fng.getResource(model);
        let gfs: any = new Grid(resource.model.db.db, mongo);
        let promises: any = [];
        busboy.on('file', function(fieldname, file, filename) {
            return promises.push(new Promise(function(resolve, reject) {
                let options;
                options = {
                    filename: filename,
                    root: resource.model.collection.name
                };
                return uploadFile(gfs, file, options, function(err, res) {
                    if (err) {
                        return reject(err);
                    }
                    let id = res._id.toString();
                    let response: any = {
                        name: res.filename,
                        size: res.length,
                        url: modifiedOptions.urlPrefix + 'file/' + model + '/' + id,
                        deleteUrl: modifiedOptions.urlPrefix + 'file/' + model + '/' + id,
                        deleteType: 'DELETE'
                    };

                    let typeFromExtension = path.extname(res.filename);
                    /*
                    Create thumbnails on ImageTragick 'safe-ish' types (according to https://lcamtuf.blogspot.co.uk/2016/05/clearing-up-some-misconceptions-around.html)
                    */
                    switch (typeFromExtension) {
                        case '.gif':
                        case '.png':
                        case '.jpg':
                        case '.jpeg':
                            // Create the thumbnail
                            let options = {
                                filename: 'thumbnail_' + res.filename,
                                root: resource.model.collection.name,
                                /*jshint -W106 */
                                metadata: {original_id: id} // original id is needed to remove thumbnail afterwards
                                /*jshint +W106 */
                            };

                            let type = typeFromExtension === '.jpeg' ? 'jpg' : typeFromExtension.slice(1,4);
                            let resize = ims().resize('100x100').quality(90).inputFormat(type).outputFormat(type);
                            let readstream = gfs.createReadStream({_id: id, root: resource.model.collection.name, fsync: true});
                            uploadFile(gfs, readstream.pipe(resize), options, function(err, res) {
                                if (err) {
                                    return reject(err);
                                }
                                response.thumbnailUrl = modifiedOptions.urlPrefix + 'file/' + model + '/thumbnail/' + res._id.toString();
                                return resolve(response);
                            });
                            break;
                        default:
                            response.thumbnailUrl = 'https://upload.wikimedia.org/wikipedia/commons/7/77/Icon_New_File_256x256.png';
                            return resolve(response);
                    }
                });
            }));
        });
        busboy.on('finish', function() {
            return Promise.all(promises)
                .then(function(results) {
                    return res.send({files: results});
                }, function(err){
                    return res.status(500).send(err);
                }) ;
        });
        return req.pipe(busboy);
    }]));
开发者ID:forms-angular,项目名称:fng-jq-upload,代码行数:92,代码来源:fng-jq-upload.ts


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