How to use busboy - 10 common examples

To help you get started, we’ve selected a few busboy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github lennym / busboy-body-parser / test / index.js View on Github external
pipe: function (s) {
                s.end('abc123');
                // ensure 'finish' event fires after files are processed
                process.nextTick(Busboy.prototype.on.withArgs('finish').args[0][1]);
            },
            truncated: true
github mlaursen / react-md / documentation / src / server / api / fakeUpload.js View on Github external
fakeUploadRouter.post('/', (req, res) => {
  // A **really** terrible fake upload by using busboy to track incoming files so
  // there is some sort of progress available in the client. Don't actually do
  // anything with the files though.
  const busboy = new BusBoy({ headers: req.headers });
  busboy.on('finish', () => {
    res.writeHead(200, { Connection: 'close' });
    res.end();
  });

  req.pipe(busboy);
});
github strues / boldr / server / routes / attachment / attachment.controller.js View on Github external
export async function uploadImage(req, res, next) {
  let fstream;
  const busboy = new Busboy({ headers: req.headers });

  busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
    // if theres no file attached, return with error
    if (filename.length === 0) {
      return next(new BadRequest('No file selected!'));
    }
    // if the file extension doesnt match the regex, return a bad request.
    if (!filename.match(regex)) {
      return next(new BadRequest('Invalid file type'));
    }
    // define temporary file path before processing.
    const tmpFilePath = path.join(process.cwd(), './public/.tmp');
    // generate a shortid for the new file name and keep the ext
    const imgId = shortId.generate();
    // take the shortid and the extension to form the new file name
    const newFileName = imgId + path.extname(filename);
github lennym / busboy-body-parser / test / index.js View on Github external
afterEach(function () {
        Busboy.prototype.on.restore();
    });
github lennym / busboy-body-parser / test / index.js View on Github external
beforeEach(function () {
        parser = bodyparser();
        req = {
            headers: {
                'content-type': 'multipart/form-data; boundary=----WebKitFormBoundaryHsAjApiShDrW2RCB',
            },
            is: sinon.stub().returns(true),
            pipe: sinon.stub()
        };
        res = {};
        next = sinon.stub();
        sinon.stub(Busboy.prototype, 'on');
    });
github uploadcare / uploadcare-upload-client / mock-server / middleware / multipart.ts View on Github external
const multipart = (ctx, next) => {
  if (ctx.request.method === 'POST') {
    const busboy = new Busboy({headers: ctx.request.headers})
    let fields = []

    busboy.on('field', (fieldName, fieldValue) => {
      fields[fieldName] = inspect(fieldValue)
    })

    busboy.on('finish', () => {
      ctx.request.multipart.fields = fields
      next()
    })

    ctx.request.pipe(busboy)
  } else {
    next()
  }
}
github vpdb / server / src / app / files / file.storage.ts View on Github external
return new Promise((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,
github streamplace / streamplace / packages / sp-uploader / src / sp-uploader.js View on Github external
.then(([apiFile]) => {
      if (!apiFile) {
        return res.sendStatus(404);
      }
      const busboy = new Busboy({ headers: req.headers });
      let haveFile = false;
      busboy.on("file", (fieldname, file, filename, encoding, mimetype) => {
        if (haveFile === true) {
          res.status(400);
          res.send("You may only upload one file at a time");
          return res.end();
        }
        haveFile = true;
        const fileOutput = fileOutputStream({
          accessKeyId: S3_ACCESS_KEY_ID,
          secretAccessKey: S3_SECRET_ACCESS_KEY,
          bucket: S3_BUCKET,
          host: S3_HOST,
          prefix: `${apiFile.id}/${filename}`
        });
        file.pipe(fileOutput);
github RocketChat / Rocket.Chat / packages / rocketchat-livechat / imports / server / rest / upload.js View on Github external
return RocketChat.API.v1.unauthorized();
		}

		const visitorToken = this.request.headers['x-visitor-token'];
		const visitor = LivechatVisitors.getVisitorByToken(visitorToken);

		if (!visitor) {
			return RocketChat.API.v1.unauthorized();
		}

		const room = RocketChat.models.Rooms.findOneOpenByVisitorToken(visitorToken, this.urlParams.rid);
		if (!room) {
			return RocketChat.API.v1.unauthorized();
		}

		const busboy = new Busboy({ headers: this.request.headers });
		const files = [];
		const fields = {};

		Meteor.wrapAsync((callback) => {
			busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
				if (fieldname !== 'file') {
					return files.push(new Meteor.Error('invalid-field'));
				}

				const fileDate = [];
				file.on('data', (data) => fileDate.push(data));

				file.on('end', () => {
					files.push({ fieldname, file, filename, encoding, mimetype, fileBuffer: Buffer.concat(fileDate) });
				});
			});
github qmit-pro / moleculer-api / src / schema / plugin / protocol / rest / handler / multipart.ts View on Github external
return new Promise((resolve, reject) => {
      let released = false;
      let exitError: Error | undefined;
      let currentStream: NodeJS.ReadableStream | undefined;

      const parser = new Busboy({
        headers: req.headers,
        defCharset: "utf8",
        limits: {
          fileSize: this.props.maxFileSize,
          files: this.props.maxFiles,
        },
      });

      const uploads: { [fieldName: string]: Upload } = {};
      const capacitors: { [fieldName: string]: WriteStream } = {};

      const release = () => {
        if (released) {
          return;
        }
        released = true;

busboy

A streaming parser for HTML form data for node.js

MIT
Latest version published 3 years ago

Package Health Score

73 / 100
Full package analysis

Popular busboy functions