How to use content-disposition - 10 common examples

To help you get started, we’ve selected a few content-disposition 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 cam-inc / viron / src / store / actions / components.js View on Github external
.then(res => {
        context.commit('application.removeNetworking', networkingId, context);
        // tokenを更新する。
        const token = res.headers['Authorization'];
        if (!!token) {
          context.commit('endpoints.updateToken', currentEndpointKey, token);
        }
        // ダウンロード指定されていればダウンロードする。
        const contentDispositionHeader = res.headers['content-disposition'];
        if (!contentDispositionHeader) {
          return res;
        }
        const downloadFileInfo = contentDisposition.parse(contentDispositionHeader);
        if (downloadFileInfo.type !== 'attachment') {
          return res;
        }
        download(res.data, downloadFileInfo.parameters.filename, res.headers['content-type']);
        return res;
      })
      .catch(err => {
github gbdev / database / scrapers / pdroms / download.js View on Github external
const request = https.get(url, function (res) {
		let filename = res.headers.date + '.' + res.headers['content-type'].replace(/\//g, '-')
		let folder = 'unknown'
		let slug = slugify(title)
		try {
			const cdHeader = res.headers['content-disposition'].replace(/filename=([^"]+?)(?:;|$)/g, 'filename="$1";').replace(/;$/, '')
			const cd = contentDisposition.parse(cdHeader)
			filename = cd.parameters.filename
			folder = slug
		}
		catch (e) { }

		const dir = PATH.join(outDir, folder)

		gamesList.push(title)

		const json = {
			title,
			slug,
			// license: "No information"
			developer: author,
			// repository: "",
			// platform: "GB",
github andrewrk / groovebasin / lib / import_url_filters.js View on Github external
download(urlString, function(err, resp) {
    if (err) return cb(err);
    var contentDisposition = resp.headers['content-disposition'];
    if (contentDisposition) {
      var filename;
      try {
        filename = parseContentDisposition(contentDisposition).parameters.filename;
      } catch (err) {
        // do nothing
      }
      if (filename) {
        decodedFilename = filename;
      }
    }
    var contentLength = parseInt(resp.headers['content-length'], 10);
    cb(null, resp, decodedFilename, contentLength);
  });
}
github mozilla / send / app / serviceWorker.js View on Github external
{
        transform(chunk, controller) {
          file.progress += chunk.length;
          controller.enqueue(chunk);
        }
      },
      function oncancel() {
        // NOTE: cancel doesn't currently fire on chrome
        // https://bugs.chromium.org/p/chromium/issues/detail?id=638494
        file.download.cancel();
        map.delete(id);
      }
    );

    const headers = {
      'Content-Disposition': contentDisposition(file.filename),
      'Content-Type': type,
      'Content-Length': size
    };
    return new Response(responseStream, { headers });
  } catch (e) {
    if (noSave) {
      return new Response(null, { status: e.message });
    }

    return new Response(null, {
      status: 302,
      headers: {
        Location: `/download/${id}/#${file.key}`
      }
    });
  }
github arangodb / arangodb / js / apps / system / _api / foxx / APP / multipart.js View on Github external
&& part.headers && typeof part.headers === 'object'
        && part.data instanceof Buffer
      )),
      `Expecting a multipart array, not ${body ? typeof body : String(body)}`
    );
    const parsedBody = {};
    for (const part of body) {
      const headers = {};
      for (const key of Object.keys(part.headers)) {
        headers[key.toLowerCase()] = part.headers[key];
      }
      const dispositionHeader = headers['content-disposition'];
      if (!dispositionHeader) {
        continue;
      }
      const disposition = contentDisposition.parse(dispositionHeader);
      if (disposition.type !== 'form-data' || !disposition.parameters.name) {
        continue;
      }
      const name = disposition.parameters.name;
      const filename = disposition.parameters.filename;
      const type = headers['content-type'];
      if (type || filename) {
        parsedBody[name] = Object.assign(part.data, {
          headers: _.omit(headers, ['content-disposition']),
          filename
        });
      } else {
        let value = part.data.toString('utf-8');
        try {
          value = JSON.parse(value);
        } catch (e) {
github codice / ddf / ui / packages / catalog-ui-search / src / main / webapp / react-component / results-export / container.tsx View on Github external
count,
        cql,
        srcs,
      })
    } else {
      const result = this.props.results[0]

      response = await exportResult(
        result.source,
        result.id,
        uriEncodedTransformerId
      )
    }

    if (response.status === 200) {
      const filename = contentDisposition.parse(
        response.headers.get('content-disposition')
      ).parameters.filename
      const contentType = response.headers.get('content-type')
      const data = await response.blob()

      saveFile(filename, 'data:' + contentType, data)
    }
  }
  handleExportOptionChange(name: string) {
github kapouer / url-inspector / lib / inspector.js View on Github external
obj.mime = "text/html";
		} else {
			obj.mime = MediaTyper.format(mimeObj);
			obj.type = mime2type(mimeObj);
		}

		var contentLength = res.headers['content-length'];
		if (contentLength != null) {
			obj.size = parseInt(contentLength);
		}
		var disposition = res.headers['content-disposition'];
		if (disposition != null) {
			debug("got content disposition", disposition);
			if (disposition.startsWith('filename=')) disposition = 'attachment; ' + disposition;
			try {
				disposition = ContentDisposition.parse(disposition);
			} catch(ex) {
				debug("Unknown Content-Disposition format", ex);
			}
			if (disposition && disposition.parameters.filename) {
				urlObj = URL.parse(disposition.parameters.filename);
			}
		}
		if (obj.title == null && urlObj.path) {
			obj.title = lexize(Path.basename(urlObj.path));
		}

		debug("(mime, type, length) is (%s, %s, %d)", obj.mime, obj.type, obj.size);
		var charset = mimeObj.parameters && mimeObj.parameters.charset;
		if (charset) {
			charset = charset.toLowerCase();
			if (charset != "utf-8") {
github zapier / zapier-platform-core / src / tools / create-file-stasher.js View on Github external
response.body &&
                  typeof response.body.pipe === 'function'
                ) {
                  newBufferStringStream = response.body;
                } else {
                  newBufferStringStream = response.content;
                }

                if (response.headers) {
                  knownLength =
                    knownLength || response.getHeader('content-length');
                  const cd = response.getHeader('content-disposition');
                  if (cd) {
                    filename =
                      filename ||
                      contentDisposition.parse(cd).parameters.filename;
                  }
                }
              } else {
                throw new Error(
                  'Cannot stash a Promise wrapped file of unknown type.'
                );
              }

              return uploader(
                result,
                newBufferStringStream,
                knownLength,
                filename,
                fileContentType
              );
            };
github alphakevin / unoconv-server / lib / storage.js View on Github external
return (req, res, next) => {
    const contentType = req.get('Content-Type');
    const contentDisp = req.get('Content-Disposition');
    if (contentType.indexOf('multipart/form-data') === 0) {
      next();
      return;
    }
    if (!contentType || !contentDisp) {
      throw new ApiError(400, 'Could not find Content-Type or Content-Disposition header');
    }
    const parsed = contentDisposition.parse(contentDisp);
    if (!parsed || !parsed.parameters || !parsed.parameters.filename) {
      throw new ApiError('invalid Content-Disposition header');
    }
    const { filename } = parsed.parameters;
    const ext = path.extname(filename);
    const newFilename = `${uuid.v4()}${ext}`;
    const filePath = `${os.tmpdir()}/${newFilename}`
    const fileStream = fs.createWriteStream(filePath);
    fileStream.on('finish', () => {
      req.file = {
        originalname: filename,
        filename: newFilename,
        path: filePath,
      };
      next();
    });
github kevva / download / index.js View on Github external
const getFilename = (res, data) => {
	const header = res.headers['content-disposition'];

	if (header) {
		const parsed = contentDisposition.parse(header);

		if (parsed.parameters && parsed.parameters.filename) {
			return parsed.parameters.filename;
		}
	}

	let filename = filenameFromPath(res);

	if (!path.extname(filename)) {
		const ext = (fileType(data) || {}).ext || getExtFromMime(res);

		if (ext) {
			filename = `${filename}.${ext}`;
		}
	}

content-disposition

Create and parse Content-Disposition header

MIT
Latest version published 3 years ago

Package Health Score

78 / 100
Full package analysis

Popular content-disposition functions