2016-12-02 73 views
0

我幾乎完成了一個問題,因爲我是Golang的新手,我基本上試圖獲取文件的絕對路徑,方法是在os.open方法中。我一直在嘗試各種東西,但沒有任何工程獲取文件絕對路徑時Golang運行時錯誤

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) 
    } 

例如,如果我硬編碼像 /Users/Documents/pictures/cats.jpg然後將文件上傳成功在os.Open字符串。當我嘗試獲取絕對路徑並將其放入os.Open時,運行時出現此錯誤單值上下文中的多值filepath.Abs​​()。有沒有其他方法可以獲得文件的路徑,以便我可以將它放入該方法中?

回答

2

根據documentation,Abs函數將返回兩個值,一個字符串和一個錯誤。

所以你不能有這樣的:

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

相反,你應該寫:

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

還要注意的是absolute_path是一個字符串了。

2

從該行的(單值上下文多值filepath.Abs​​())代碼的編譯器錯誤

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

是告訴你,filepath.Abs將返回多個參數和string只需要一個參數。

filepath.Abs返回stringerror

代碼應該是:

ap, err := filepath.Abs(header.Filename) 
if err != nil { 
    // handle error 
} 
+0

完美非常感謝你,它的工作 –

相關問題