How to use the mime-types.extension function in mime-types

To help you get started, we’ve selected a few mime-types 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 OpenSprites / OpenSprites-next / server / main.js View on Github external
app.get(`/resources/:id/download/:f?`, async function(req, res) {
  let resource
  try {
    resource = await db.Resource.findById(req.params.id)
  } catch(err){
    console.log(err)
    res.status(404).render('404', {
      user: req.session.user,
      csrfToken: req.csrfToken()
    })
    return
  }

  if(!req.params.f) {
    let title = resource.name.replace(/\ /g, '-')
    let type = require('mime-types').extension(resource.type) || 'mp3'
    let f = `${sanitize(title)}.${type}`

    res.redirect(`/resources/${req.params.id}/download/${f}`)
  } else {
    try {
      await resource.incrementDownloads(req.ip)
      for(let owner of resource.owners) {
        let u = await User.findByUsername(owner)
        if(owner != req.session.user)
          u.sendMessage('download', 'resource', 'Resource', resource._id, 1)
      }
    } catch(err){
      console.log(err)
      // continue to download anyway
    }
    if(resource.script) {
github diplomatiegouvfr / hornet-js / hornet-js-components / src / upload-file / upload-file-field.jsx View on Github external
UploadFileField.prototype.toJavaScript = function (uploadedFile) {
    if (uploadedFile) {
        if (this.widget && this.widget.attrs.maxSize && uploadedFile.size > this.widget.attrs.maxSize) {
            var maxSizeInMB = utils._.round(this.widget.attrs.maxSize / (1024 * 1024), 2);
            throw newforms.ValidationError(this.errorMessages.maxSize, {code:"maxLength", params: {maxSizeInMB: maxSizeInMB}});
        }
        if (this.widget && this.widget.attrs.accept) {

            var extension = "";
            /* recuperation de l'extension du fichier */
            /* par défaut, on recupere celle qui est associée au mime type : */
            if (uploadedFile.type) {
                extension = mime.extension(uploadedFile.type);
            }
            /* par contre, si l'extension est présente dans le nom du fichier */
            /* on la prend en priorité : */
            if (uploadedFile.name && uploadedFile.name.indexOf(".") != -1) {
                extension = utils._.last(uploadedFile.name.split("."));
            }

            /* comparaison de l'extension du fichier avec la liste des extensions autorisées (accept) */
            /* _.some renvoie true si au moins une des extensions autorisées correspond */
            var allowedType = utils._.some(this.widget.attrs.accept, function (accept) {
                return accept === "." + extension
            });
            if (!allowedType) {
                throw newforms.ValidationError(this.errorMessages.invalid, {code: "invalid", params: {fileTypeList:this.widget.attrs.accept}});
            }
        }
github Kong / insomnia / packages / insomnia-app / app / ui / containers / app.js View on Github external
// Start loading
    handleStartLoading(requestId);

    try {
      const responsePatch = await network.send(requestId, environmentId);
      const headers = responsePatch.headers || [];
      const header = getContentDispositionHeader(headers);
      const nameFromHeader = header ? header.value : null;

      if (
        responsePatch.bodyPath &&
        responsePatch.statusCode >= 200 &&
        responsePatch.statusCode < 300
      ) {
        const extension = mime.extension(responsePatch.contentType) || 'unknown';
        const name =
          nameFromHeader || `${request.name.replace(/\s/g, '-').toLowerCase()}.${extension}`;

        let filename;
        if (dir) {
          filename = path.join(dir, name);
        } else {
          filename = await this._getDownloadLocation();
        }

        const to = fs.createWriteStream(filename);
        const readStream = models.response.getBodyStream(responsePatch);

        if (!readStream) {
          return;
        }
github dadi / web / dadi / lib / view / public.js View on Github external
: false

  // Cache
  const cacheExt =
    compressible(contentType) && help.canCompress(arg.req.headers)
      ? `.${help.canCompress(arg.req.headers)}`
      : null

  const cacheInfo = {
    name: crypto
      .createHash('sha1')
      .update(arg.file.url)
      .digest('hex'),
    opts: {
      directory: {
        extension: mime.extension(contentType) + cacheExt
      }
    }
  }

  // Headers
  var headers = {
    'Cache-Control':
      config.get('headers.cacheControl')[contentType] ||
      'public, max-age=86400',
    'Content-Type': contentType
  }

  if (shouldCompress) headers['Content-Encoding'] = shouldCompress

  // If it's compressible, it's cachable so check the cache or create a new cache file
  if (
github ladjs / nodemailer-base64-to-s3 / index.js View on Github external
async function transformImage({ original, start, mimeType, base64, end }) {
    // get the image extension
    let extension = mime.extension(mimeType);
    // convert and optimize the image if it is an SVG file
    if (extension === 'svg') extension = 'png';
    // if we already cached the base64 then return it
    const hash = revHash(`${extension}:${base64}`);
    let buffer;
    if (cache[hash]) {
      buffer = cache[hash];
      debug(`hitting cache for ${hash}`);
    } else {
      // create a buffer of the base64 image
      // and convert it to a png
      buffer = Buffer.from(base64, 'base64');
      const lipo = new Lipo();
      buffer = await lipo(buffer)
        .png()
        .toBuffer();
github nethruster / nethloader-backend / src / index.js View on Github external
fileFilter: (req, file, cb) => {
    cb(null, supportedExtensions.includes(mime.extension(file.mimetype)))
  }
}).single('file')
github yarnaimo / vanilla-clipper / src / data / Resource.ts View on Github external
async createVersion({
        buffer,
        hash,
        mimetype,
    }: {
        buffer: Buffer
        hash?: string
        mimetype?: string
    }) {
        const outputDir = DateTime.local().toFormat('yyyyMMdd')

        const id = ulid()
        const ext = mimetype && extension(mimetype)
        const filename = ext ? `${id}.${ext}` : id
        const path = `${outputDir}/${filename}`

        await outputFile(resourcePath(outputDir, filename), buffer)

        if (hash) {
            const version = {
                createdAt: now(),
                hash,
                path,
            } as Version

            this.versions.push(version)
            this.save()

            return version
github inrupt / wac-ldp / src / lib / storage / BlobTreeNssCompat.ts View on Github external
function contentTypeToExtension (contentType: string): string {
  return mime.extension(contentType) || ''
}
function filePathForContentType (filePath: string, contentType: string) {