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 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。