4

How can I use the <img> tag to display a local image in Go?

I've tried the following:

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

where rootdir = os.Getwd() and fileName is the name of the file.

If I try http.ServeFile with the same path then I can download the image, however I would like to embed it in the webpage itself.

4

3 回答 3

8

我会先说我的 Go 知识充其量是很糟糕的,但我所做的少数实验涉及到这一点,所以也许这至少会为你指明正确的方向。基本上,下面的代码使用 Handle 来处理根目录中文件夹中的文件(在我的情况下是/images/)。然后,您可以在标签中进行硬编码,也可以像以前一样使用,制作第一个参数。images/home/username/go/images/<img>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)
}
于 2012-10-15T03:59:23.470 回答
2

也许您可以使用数据 URI

于 2012-10-15T03:30:21.950 回答
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()
}
于 2021-06-11T21:27:14.983 回答