dsp1836 2012-10-15 03:00
浏览 174
已采纳

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

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.

  • 写回答

2条回答 默认 最新

  • douchao5864 2012-10-15 03:59
    关注

    I'll preface this by saying my Go knowledge is atrocious at best, but the few experiments I've done have involved this a bit, so maybe this will at least point you in the right direction. Basically, the below code uses a Handle for anything under /images/ that serves files from the images folder in your root directory (in my case it was /home/username/go). You can then either hardcode /images/ in your <img> tag, or use path.Join() as you did before, making images the first argument.

    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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘