6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Go】バイナリファイルからContent-Typeを取得する

Last updated at Posted at 2020-03-12

ファイルからContent-Typeを検出

バイナリの先頭ヘッダ512byteを読んで取得後、ポインタをもとに戻す

.go
func DetectFileContentType(file *os.File) string {
	// 最初の512bytesを読む
	buffer := make([]byte, 512)
	file.Read(buffer)

	// 有効なMIMEタイプでない場合は「application/octet-stream」が返る
	contentType := http.DetectContentType(buffer)

	// 読み取りポインターをリセットする
	file.Seek(0, 0)

	return contentType
}

ファイルタイプを調べるライブラリ(h2non/filetype)によっては先頭261byteだけ読んでるのとかあったんですけど、このヘッダってどこまでとか定義されてたりするんですかね?
(ちなみに上記のライブラリで検出できなかったMP4の動画ファイルがあったのでライブラリ使わず処理を書きました)

参考URL

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?