doutui7955 2017-01-09 21:01
浏览 71

Golang图片和上传路径混合结果

I have successfully been able to upload images to my ImageStore account however I have had to hardcode each file path . My issue is that my images reside outside of my GoPath are there any way that I can get the actual directory to my images without hardcoding it ? For instance

GoPath = "/Users/IH/Documents/go"

Actual Image Path = "/Users/IH/Documents/pictures/horse_PNG2538.png"

Path I'm getting = "/Users/IH/Documents/go/src"

I need to get the correct path of an image because user's will be able to Upload their images and obviously they are all going to have different paths to their images . This is the code I have

myfile, handler, err := r.FormFile("uploadImage")
if err != nil {
    fmt.Println(err)

    return
}
defer myfile.Close()


pwd, err := os.Getwd()
if err != nil {
    fmt.Println(err)
    os.Exit(1)
}
fmt.Println(pwd)

file,err := os.Open(pwd + handler.Filename)

defer file.Close()
if err != nil {
    fmt.Printf("err opening file: %s", err)
}

The pwd gives me the path /Users/IH/Documents/go/src which offcourse gives me an error because the image is not found there . If I for instance hard code the correct image address then it uploads such as

file,err := os.Open("/Users/IH/Documents/pictures/horse_PNG2538.png")

then the image gets uploaded . Again this image is coming from this directory /Users/IH/Documents/pictures/ how can I spot that directory on image upload without hardcoding it ? any suggestions would be great

  • 写回答

1条回答 默认 最新

  • douqianxian7008 2017-01-09 21:13
    关注

    The "os/user" package allows you to determine the directory of the current user like so:

    package main
    
    import (
        "fmt"
        "log"
        "os/user"
    )
    
    func main() {
        usr, err := user.Current()
        if err != nil {
            log.Fatal(err)
        }
    
        fmt.Println(usr.HomeDir)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度