5

I am working on an API which is fetching file data as arraybuffer type. What my main question is there any of knowing what is the mime type of the file from the arraybuffer as I need to convert it to BLOB to view the file.

var file1 = new Blob([response], { type: file.type });
var fileURL = URL.createObjectURL(file1);

In the above code snippet, the response is an arraybuffer and the mime type I got is by storing it while uploading in a variable. But now the scenario is I don't have any mime type in my hand so I need a way to get it.

This is my response header: header

And this is my response body sample: body

Can anyone suggest me anything ?

Avishek
  • 524
  • 16
  • 38

2 Answers2

2

I found this package below which is very interesting. It parses the array buffer/blob/stream and try to guess its extension and mime type if it were a file. Obviously it is not exhaustive but you can find the extension list in the readme. Works on node and browser. Works for my needs though.

Here is the repo link : https://github.com/sindresorhus/file-type

2

Alternative to file-type which seems to also use magic signature :

function getMimeTypeFromArrayBuffer(arrayBuffer) {
  const uint8arr = new Uint8Array(arrayBuffer)

  const len = 4
  if (uint8arr.length >= len) {
    let signatureArr = new Array(len)
    for (let i = 0; i < len; i++)
      signatureArr[i] = (new Uint8Array(arrayBuffer))[i].toString(16)
    const signature = signatureArr.join('').toUpperCase()

    switch (signature) {
      case '89504E47':
        return 'image/png'
      case '47494638':
        return 'image/gif'
      case '25504446':
        return 'application/pdf'
      case 'FFD8FFDB':
      case 'FFD8FFE0':
        return 'image/jpeg'
      case '504B0304':
        return 'application/zip'
      default:
        return null
    }
  }
  return null
}

inspired from https://medium.com/the-everyday-developer/detect-file-mime-type-using-magic-numbers-and-javascript-16bc513d4e1e

Remy Mellet
  • 1,675
  • 20
  • 23
  • More specifically, `signatureArr[i] = (new Uint8Array(arrayBuffer))[i].toString(16)` should be replaced with `signatureArr[i] = (new Uint8Array(arrayBuffer))[i].toString(16).padStart(2, "0")`. Moreover, it's recommended to use the signature database: [https://gist.github.com/Qti3e/6341245314bf3513abb080677cd1c93b](https://gist.github.com/Qti3e/6341245314bf3513abb080677cd1c93b) – ChangUk May 25 '23 at 08:46