donglian3055 2016-12-02 22:36
浏览 222
已采纳

获取文件绝对路径时出现Golang运行时错误

I am almost done with an issue that has stomped me as I am new to Golang, I am basically trying to get the absolute path of a file inside the os.open method. I have been trying all types of things but nothing works

  func UploadProfile(w http.ResponseWriter, r *http.Request) {
    r.ParseForm()
    infile, header, err := r.FormFile("upload_file")
    if err != nil {
        http.Error(w, "Error parsing uploaded file: "+err.Error(), http.StatusBadRequest)
        return
    }
    defer infile.Close()


       absolue_path := string(filepath.Abs(header.Filename))
                  // I want to get the absolute path in os.Open
    file, err :=  os.Open(absolute_path)
    }

for instance if I hard code the string in the os.Open like /Users/Documents/pictures/cats.jpg then the file uploads successfully . When i try to get the absolute path and put it inside the os.Open I get this error on runtime multiple-value filepath.Abs() in single-value context . Is there any other way that I can get the path of the file so that I can put it inside that method ?

  • 写回答

2条回答 默认 最新

  • doushi7394 2016-12-02 22:41
    关注

    According to documentation, Abs function will return TWO values, one string and one error.

    So you can not have something like:

    absolute_path := string(filepath.Abs(header.Filename))
    

    instead, you should write:

    absolute_path, err := filepath.Abs(header.Filename)
    

    Also note that absolute_path is a string already.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 能给我一些人生建议吗
  • ¥15 mac电脑,安装charles后无法正常抓包
  • ¥18 visio打开文件一直显示文件未找到
  • ¥15 请教一下,openwrt如何让同一usb储存设备拔插后设备符号不变?
  • ¥30 使用quartz框架进行分布式任务定时调度,启动了两个实例,但是只有一个实例参与调度,另外一个实例没有参与调度,不知道是为什么?请各位帮助看一下原因!!
  • ¥50 怎么获取Ace Editor中的python代码后怎么调用Skulpt执行代码
  • ¥30 fpga基于dds生成幅值相位频率和波形可调的容易信号发生器。
  • ¥15 R语言shiny包和ncdf4包报错
  • ¥15 origin绘制有显著差异的柱状图和聚类热图
  • ¥20 simulink实现滑模控制和pid控制对比,提现前者优势