golang从零起步

golang http.ServeFile读取图片(显示图片)

2019-01-12  本文已影响0人  次序
//前端显示图片
func DownloadHandler(w http.ResponseWriter, r *http.Request) {

    //imgpath := "C:\\Users\\cixu\\Pictures\\"+mux.Vars(r)["imgid"]
    imgpath := "C:\\Users\\cixu\\Pictures\\1.jpg"
//imgpath := "./uploads/"+mux.Vars(r)["imgid"]

    http.ServeFile(w, r, imgpath)
}
/前端显示图片
func DownloadHandler(w http.ResponseWriter, r *http.Request) {
    imgs_dir := "/home/xlxweichat/imgs/"
    if "windows" == runtime.GOOS {
        imgs_dir = "C:\\Users\\cixu\\Desktop\\1\\"
    }

    //imgpath := "./uploads/"+mux.Vars(r)["imgid"]
    imgpath := imgs_dir+mux.Vars(r)["imgid"]
    //imgpath := "C:\\Users\\cixu\\Pictures\\"+mux.Vars(r)["imgid"]

    //http.ServeFile(w, r, imgpath)
    w.Header().Set("Content-Type", "image/jpg")
    w.Header().Set("Content-Disposition",fmt.Sprintf("inline; filename=\"%s\"",mux.Vars(r)["imgid"]))

    file, err := ioutil.ReadFile(imgpath)
    if err != nil {
        fmt.Fprintf(w,"查无此图片")
        return
    }
    w.Write(file)
}
上一篇下一篇

猜你喜欢

热点阅读