我正在尝试获取上传到我的服务器中的mime类型的文件。
.xlsx和.docx文件mime类型出现在application/zip中。我尝试解压缩文件并读取"_rels/.rels“类型的文件。我的疑问是,在读取这个特定的文件时,我应该为读取文件保留的最大大小是多少,如果Target是"xl/workbook.xml“,我可以假定它是xlsx类型的吗?
我的代码如下
file, fileHeader, err := r.FormFile("file")
buffer := make([]byte, 512)
_, err = file.Read(buffer)
if err != nil {
fmt.Println(err)
}
contentType := http.DetectContentType(buffer)
if contentType == "application/zip" {
r, err := zip.NewReader(file, fileHeader.Size)
if err != nil {
fmt.Println(err)
}
for _, zf := range r.File {
if zf.Name == "_rels/.rels" {
fmt.Println("rels")
rc, err := zf.Open()
if err != nil {
fmt.Println("Rels errors")
}
const BufferSize = 1000
buffer := make([]byte, BufferSize)
defer rc.Close()
bytesread, err := rc.Read(buffer)
if err != nil {
if err != io.EOF {
fmt.Println(err)
}
}
fmt.Println("bytes read: ", bytesread)
fmt.Println("bytestream to string: ", string(buffer[:bytesread]))
fmt.Println(rc)
}
}
}
var arr []byte
w.Header().Set("Content-Type", "application/json")
w.Write(arr)}
我得到的输出是
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/extended-properties" Target="docProps/app.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>关于如何阅读.doc或.xls有什么建议吗?
发布于 2018-09-11 06:45:18
不幸的是,html包中的DetectContentType仅限于它可以检测到的mime类型。
你只要检查文件签名就行了。file signatures是一个很好的文件签名资源
免责声明:我是mimetype的作者。
- pure go, no c bindings
- can be extented to detect new mime types
- has issues with files which pass as more than one mime type (ex: xlsx and docx passing as zip) because it stores matching functions in a map, thus it does not guarantee the order of traversal- needs libmagic-dev installed
- can be extended, albeit harder... `man magic`- pure go, no c bindings
- higher number of detected mime types than `filetype`
- is thread safe
- can be extendedhttps://stackoverflow.com/questions/51209439
复制相似问题