chrome and safari don't render images in html template served by a go server with Content-Length is set

huangapple go评论73阅读模式
英文:

chrome and safari don't render images in html template served by a go server with Content-Length is set

问题

我在GridFS上存储了一些图像,并通过一个简单的Go Web服务器提供资源。

func GetFile(w http.ResponseWriter, r *http.Request) {
    fileObjectId := r.URL.Path[len("/file/"):]
    gfs := db.GridFS("fs")
    file, err := gfs.OpenId(bson.ObjectIdHex(fileObjectId))
    if err != nil {
        panic("file not found")
    }
    w.Header().Set("Content-Length", strconv.FormatInt(file.Size(), 10))
    w.Header().Set("Content-Type", file.ContentType())

    buff := make([]byte, 8192)
    nread, _ := file.Read(buff)
    for nread > 0 {
        w.Write(buff)
        nread, _ = file.Read(buff)
    }
}

问题:

a. 如果将图像放在HTML模板的img标签中,Chrome和Safari无法渲染图像,但Firefox可以正常显示图像。

b. 如果直接在Chrome和Safari中访问图像,一切正常。

c. 如果移除Content-Length,Chrome和Safari可以在HTML模板中加载图像。

d. 我使用Python和pymongo编写了相同的处理程序,并设置了Content-Length和Content-Type,在Chrome和Safari中可以正常工作。

英文:

I stored some images on GridFS and served the resource with a simple Go web server.

func GetFile(w http.ResponseWriter, r *http.Request) {
    fileObjectId := r.URL.Path[len("/file/"):]
    gfs := db.GridFS("fs")
    file, err := gfs.OpenId(bson.ObjectIdHex(fileObjectId))
    if err != nil {
	    panic("file not found")
    }
    w.Header().Set("Content-Length", strconv.FormatInt(file.Size(), 10))
    w.Header().Set("Content-Type", file.ContentType())
    
    buff := make([]byte, 8192)
    nread, _ := file.Read(buff)
    for nread > 0 {
	    w.Write(buff)
 	    nread, _ = file.Read(buff)
    }
}

The problems:

a. Images don't render in Chrome and Safari if they are placed in img tag in a html template. But firefox does display images pretty well.

b. If access images directly in Chrome and Safari, everything works fine.

c. By removing Content-Length, Chrome and Safari can load images in a html template.

d. I code the same handler with python and pymongo, set both Content-Length and Content-Type, it works in Chrome and Safari.

答案1

得分: 2

w.Write(buff)这行代码总是写入8192字节,这导致你的HTTP正文的总长度与文件大小不相等。

英文:

the line w.Write(buff) always to write 8192 bytes, which cause the total length of you HTTP body not equals to the file size.

huangapple
  • 本文由 发表于 2015年6月24日 15:39:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/31020545.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定