Golang 如何检测一个文件的内容类型

Golang 如何检测一个文件的内容类型

考虑到我们想在Golang中获得一个文件的内容类型,无论出于什么原因。为了做到这一点,我们必须首先知道如何打开该文件,并将其部分字节读入一个缓冲区片,然后我们将其传递给一个函数,以帮助我们检测文件的类型。

第1步是打开我们想检查其类型的文件。

打开文件

考虑到我们有一个名为 sample.pdf 的文件,其 内容类型 是我们想知道的。为了打开该文件,我们需要按照下面的代码片段所示进行操作。

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

if err != nil {
   panic(err)
}

defer file.Close()
Go

在上面的片段中,我们正在打开一个名为 sample.pdf 的文件,然后如果我们遇到任何错误,我们将调用 panic 函数。

注意,我们还推迟了文件的 Close() 方法,这总是一个好的做法。

从文件中读取数据

下一步是从文件中读取数据,我们可以在 os 包中的 Read() 方法的帮助下做到这一点。

下面所示的代码片段表示我们如何从文件中读取数据,然后将其存储在一个缓冲区中供以后使用。

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

buf := make([]byte, 512)

_, err := out.Read(buf)

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

检测内容类型

现在,最后一步是调用 http 包为我们提供的 DetectContentType() 函数。

下面是完整的程序代码 –

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 run main.go ,那么我们将在终端得到以下输出。

Content Type: application/pdf
Go

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册