1、URL格式
package main
import (
"fmt"
"io"
"mime"
"net/http"
"path"
)
func main() {
res, err := GetFileInfo("https://pic.616pic.com/ys_bnew_img/00/02/37/PlF9pGxaEh.jpg")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(res)
}
type FileInfo struct {
FileName string `json:"fileName"`
FileSize string `json:"fileSize"`
Mimetype string `json:"mimetype"`
}
func GetFileInfo(url string) (res *FileInfo, err error) {
res = new(FileInfo)
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// 读取响应体的前 512 个字节
buf := make([]byte, 512)
_, err = io.ReadFull(resp.Body, buf)
if err != nil {
return
}
// 使用 http.DetectContentType 检测 MIME 类型
res.Mimetype = http.DetectContentType(buf)
fmt.Println("Mimetype:", res.Mimetype)
contentDisposition := resp.Header.Get("Content-Disposition")
_, params, errs := mime.ParseMediaType(contentDisposition)
if errs != nil {
// 如果 Content-Disposition 不可用,从 URL 解析文件名
res.FileName = path.Base(url)
fmt.Println("Filename path.Base:", res.FileName)
// 解析后缀名
fileExt := path.Ext(url)
fmt.Println("File Extension2:", fileExt)
} else {
// 如果 Content-Disposition 可用,使用它获取文件名
fileName, ok := params["filename"]
if ok {
res.FileName = fileName
fmt.Println("Filename params: ", fileName)
// 解析后缀名
fileExt := path.Ext(fileName)
fmt.Println("File Extension1:", fileExt)
}
}
// 获取文件大小
res.FileSize = resp.Header.Get("Content-Length")
if res.FileSize != "" {
fmt.Println("fileSize Content Length:", res.FileSize)
} else {
fmt.Println("Content Length not provided")
}
return
}
2、本地文件路径
package main
import (
"fmt"
"mime"
"os"
"path/filepath"
"github.com/spf13/cast"
)
func main() {
res, err := GetFileInfo("./img/WechatIMG8.jpg")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Print(res)
}
type FileInfo struct {
FileName string `json:"fileName"`
FileSize string `json:"fileSize"`
Mimetype string `json:"mimetype"`
}
func GetFileInfo(url string) (res *FileInfo, err error) {
res = new(FileInfo)
extension := filepath.Ext(url)
res.Mimetype = mime.TypeByExtension(extension)
var file *os.File
file, err = os.Open(url)
if err != nil {
return nil, err
}
defer file.Close()
var fileInfo os.FileInfo
fileInfo, err = file.Stat()
if err != nil {
return
}
res.FileName = fileInfo.Name()
if err != nil {
return
}
res.FileSize = cast.ToString(fileInfo.Size())
if err != nil {
return
}
return
}