How to get mime type of an array buffer object?
Asked Answered
L

2

7

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 ?

Leucippus answered 11/11, 2020 at 7:12 Comment(2)
Couldn't you get it from the response headers?Seavir
@AndreiGătej please refer my updated question. I am not getting any mime type in response headerLeucippus
W
4

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

Wasp answered 13/2, 2023 at 18:12 Comment(1)
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/6341245314bf3513abb080677cd1c93bBigener
A
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

Abduce answered 2/9, 2021 at 22:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.