go 语言识别文件 content type

青苗 青苗 | 355 | 2022-08-04

上传文件如果是只允许上传指定文件,可以识别文件扩展名来区分,但是着并不是最优最准确解决方案。本文介绍 go 语言读取文件头的方式识别 contentType 来确定文件类型。

代码如下:

package main

import (
   "fmt"
   "net/http"
   "os"
)

func main() {

   // Open the file whose type you
   // want to check
   file, err := os.Open("sample.pdf")

   if err != nil {
      panic(err)
   }

   defer file.Close()

   // Get the file content
   contentType, err := GetFileContentType(file)

   if err != nil {
      panic(err)
   }

   fmt.Println("Content Type of file is: " + contentType)
}

func GetFileContentType(ouput *os.File) (string, error) {

   // to sniff the content type only the first
   // 512 bytes are used.

   buf := make([]byte, 512)

   _, err := ouput.Read(buf)

   if err != nil {
      return "", err
   }

   // the function that actually does the trick
   contentType := http.DetectContentType(buf)

      return contentType, nil
}
文章标签: Go
推荐指数:

真诚点赞 诚不我欺~

go 语言识别文件 content type

点赞 收藏 评论

关于作者

青苗
青苗

青苗幼儿园园长

等级 LV5

粉丝 20

获赞 47

经验 1182