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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)