How to use form-data - 10 common examples

To help you get started, we’ve selected a few form-data 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 TEIC / romajs / test / setup.js View on Github external
import * as FormData from 'form-data'
import { DOMParser, XMLSerializer } from 'xmldom'
import { JSDOM } from 'jsdom'

global.DOMParser = DOMParser
global.XMLSerializer = XMLSerializer
global.FormData = FormData.default
global.Blob = (strings, encoding) => {return Buffer.from(strings[0], encoding)}
global.usejsdom = (doc) => {
  // Switch document to jsdom
  const jdom = new JSDOM(new XMLSerializer().serializeToString(doc), {contentType: 'text/xml'})
  return jdom.window.document
}
github cofacts / rumors-api / src / graphql / queries / Search.js View on Github external
async resolve(rootValue, { text, findInCrawled }) {
    const crawledFormData = new FormData();

    // Avoid hitting TooManyClauses exception. Default is 1024 clauses,
    // and we are using unigram so text length = clause number.
    // https://wiki.apache.org/lucene-java/LuceneFAQ#Why_am_I_getting_a_TooManyClauses_exception.3F
    //
    const truncatedText = text.slice(0, 1024);
    crawledFormData.append('content', truncatedText);

    const [elasticResult, crawledResult] = await Promise.all([
      client.msearch({
        body: [
          { index: 'articles', type: 'basic' },
          { query: { more_like_this: { fields: ['text'], like: text, min_term_freq: 1, min_doc_freq: 1, minimum_should_match: '10<70%' } } },
          { index: 'replies', type: 'basic' },
          { query: { more_like_this: { fields: ['versions.text'], like: text, min_term_freq: 1, min_doc_freq: 1, minimum_should_match: '10<70%' } } },
        ],
github electron-userland / electron-forge / packages / publisher / bitbucket / src / PublisherBitbucket.ts View on Github external
const appPassword = process.env.BITBUCKET_APP_PASSWORD;
    const username = process.env.BITBUCKET_USERNAME;
    const auth = { appPassword, username, ...config.auth || {} };
    const apiUrl = `https://api.bitbucket.org/2.0/repositories/${config.repository.owner}/${config.repository.name}/downloads`;
    const encodedUserAndPass = Buffer.from(`${auth.username}:${auth.appPassword}`).toString('base64');

    if (!(hasRepositoryConfig && config.repository.owner && config.repository.name)) {
      throw new Error('In order to publish to Bitbucket you must set the "repository.owner" and "repository.name" properties in your Forge config. See the docs for more info');
    }

    if (!auth.appPassword || !auth.username) {
      throw new Error('In order to publish to Bitbucket provide credentials, either through "auth.appPassword" and "auth.username" properties in your Forge config or using BITBUCKET_APP_PASSWORD and BITBUCKET_USERNAME environment variables');
    }

    for (const [index, makeResult] of makeResults.entries()) {
      const data = new FormData();

      for (const artifactPath of makeResult.artifacts) {
        data.append('files', fs.createReadStream(artifactPath));
      }

      // If we are not supposed to override an existing version, we'll check check if any of
      // the files exist first
      if (!replaceExistingFiles) {
        await asyncOra('Checking if artifacts have been published previously', async () => {
          for (const artifactPath of makeResult.artifacts) {
            const fileName = path.basename(artifactPath);

            const response = await fetch(`${apiUrl}/${fileName}`, {
              headers: {
                Authorization: `Basic ${encodedUserAndPass}`,
              },
github Mangeneh / akkaskhooneh-frontend / src / pages / profileEdit / ProfileEdit.js View on Github external
changeImage() {
    const { imageSource, imageFile } = this.state;
    const formData = new FormData();
    formData.append('profile_picture', {
      uri: imageSource, // your file path string
      name: 'my_photo.jpg',
      type: imageFile.mime,
    });
    this.props.changeProfilePic(formData)
      .then((response) => {
        this.onSuccess();
      })
      .catch((error) => {
        this.onFail();
      });
  }
}
github prisma-archive / graphcool-templates / outdated / file-handling / file-proxy / simple-file-proxy.js View on Github external
form.on('part', part => {
    // We construct a new form for posting to the actual Graphcool File API
    const formdata = new formData();

    // To reduce memory footprint for large file uploads, we use streaming
    formdata.append('data', part, {filename: part.filename, contentType: part['content-type']});

    // Post the constructed form to the Graphcool File API
    request.post(graphCoolFileEndpoint,
      {
        headers: {'transfer-encoding': 'chunked'},
        _form: formdata
      }, (err, resp, body) => {
        const result = JSON.parse(body);

        // The File API has created a File node. We need to update the URL to
        // point to our own endpoint. Unfortunately, we can't, so we use a new
        // field on the File Type to store our URL.
        const query = `
github fox1t / fastify-multer / test / disk-storage.ts View on Github external
it('should process parser/form-data POST request', function(done) {
    const form = new FormData()
    const parser = upload.single('small0')

    form.append('name', 'Multer')
    form.append('small0', file('small0.dat'))

    submitForm(parser, form, function(err, req) {
      assert.ifError(err)

      assert.equal(req.body.name, 'Multer')

      assert.equal(req.file.fieldname, 'small0')
      assert.equal(req.file.originalname, 'small0.dat')
      assert.equal(req.file.size, fileSize(req.file.path))
      done()
    })
  })
github achingbrain / it / test / index.js View on Github external
test('it parses files from a multipart request', async (t) => {
  const formData = new FormData()
  formData.append('file-1.txt', Buffer.from('file 1 contents'))
  formData.append('file-2.txt', Buffer.from('file 2 contents'))

  const result = await fetch(`http://localhost:${port}`, {
    method: 'POST',
    headers: formData.getHeaders(),
    body: formData
  })

  t.is(result.status, 200)

  const response = await result.json()

  t.deepEqual(response, {
    'file-1.txt': 'file 1 contents',
    'file-2.txt': 'file 2 contents'
github Mangeneh / akkaskhooneh-frontend / src / pages / addPostInfo / actions.js View on Github external
export const sendPost = (imageSource, caption, tags) => {
  const formData = new FormData({});
  formData.append('picture', {
    uri: imageSource,
    name: 'my_photo.jpg',
    type: 'image/jpeg',
  });
  formData.append('caption', caption);
  if (tags.length > 0) {
    formData.append('tags', tags.toString());
  }
  return {
    type: Actions.SEND_POST,
    payload: {
      request: {
        method: RequestMethods.POST,
        url: Server.SEND_POST,
        data: formData,
github IanMitchell / aquarius / src / bot / commands / deschtimes.js View on Github external
aquarius.onCommand(/^release\s(?<show>.+)$/i, async (message, { groups }) => {
    log(`Marking ${groups.show} as done`);

    try {
      aquarius.loading.start(message.channel);

      const body = new FormData();
      body.append('platform', 'discord');
      body.append('channel', message.guild.id);
      body.append('name', groups.show.trim());
      body.append('username', message.author.id);
      body.append('auth', SHOWTIMES.KEY);

      const response = await fetch(`${SHOWTIMES.SERVER}/release`, {
        method: 'PUT',
        body,
      });
      const data = await response.json();

      message.channel.send(data.message);
      analytics.trackUsage('release', message);
    } catch (error) {
      log(error);
github nullcc / ts-retrofit / src / dataResolver.ts View on Github external
public resolve(headers: any, data: any): any {
    const formData = new FormData();
    for (const key in data) {
      if (data[key].filename) {
        formData.append(key, data[key].value, { filename: data[key].filename });
      } else {
        if (Array.isArray(data[key].value)) {
          for (const element of data[key].value) {
            formData.append(key, element);
          }
        } else {
          formData.append(key, data[key].value);
        }
      }
    }
    return formData;
  }
}

form-data

A library to create readable "multipart/form-data" streams. Can be used to submit forms and file uploads to other web applications.

MIT
Latest version published 2 years ago

Package Health Score

77 / 100
Full package analysis