在Go中使用<img>标签显示本地图片

4

我该如何使用 <img> 标签在 Go 中显示本地图片?

我已经尝试了以下方法:

fmt.Fprintf(w, "</br><img src='" + path.Join(rootdir,  fileName) + "' ></img>") 

其中rootdir = os.Getwd(),fileName是文件名。

如果我使用相同的路径尝试http.ServeFile,那么我可以下载图片,但是我想将其嵌入到网页中。

3个回答

8
我先声明一下,我的Go语言知识很糟糕,但我做过一些实验,其中涉及了这个问题,所以也许我的回答能够给你一些方向。基本上,下面的代码使用了一个 Handle 来处理 /images/ 下的所有内容,并从根目录下的 images 文件夹中提供文件(在我的情况下是 /home/username/go)。然后,你可以在<img>标签中硬编码/images/,或者像之前一样使用 path.Join(),把images作为第一个参数即可。
package main

import (
  "fmt"
  "net/http"
  "os"
  "path"
)


func handler(w http.ResponseWriter, r *http.Request) {
  fileName := "testfile.jpg"
  fmt.Fprintf(w, "<html></br><img src='/images/" + fileName + "' ></html>")
}

func main() {
  rootdir, err := os.Getwd()
  if err != nil {
    rootdir = "No dice"
  }

  // Handler for anything pointing to /images/
  http.Handle("/images/", http.StripPrefix("/images",
        http.FileServer(http.Dir(path.Join(rootdir, "images/")))))
  http.HandleFunc("/", handler)
  http.ListenAndServe(":8080", nil)
}

2

0
这对我有用:
package main

import (
   "io"
   "net/http"
   "os"
)

func index(w http.ResponseWriter, r *http.Request) {
   f, e := os.Open(r.URL.Path[1:])
   if e != nil {
      panic(e)
   }
   defer f.Close()
   io.Copy(w, f)
}

func main() {
   http.HandleFunc("/", index)
   new(http.Server).ListenAndServe()
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接