英文:
Golang how can I get full file path
问题
我一直在搜索,但找不到在Go语言中获取完整文件路径的方法。我有一个常规的HTML表单,然后我尝试在后端获取所有的信息。
<form method="post" enctype="multipart/form-data" action="/uploads">
<p><input type="file" name="my file" id="my file"></p>
<p>
<input type="submit" value="Submit">
</p>
</form>
func upload() {
f, h, err := r.FormFile("my file")
if err != nil {
log.Println(err)
http.Error(w, "Error Uploading", http.StatusInternalServerError)
return
}
defer f.Close()
println(h.Filename)
}
// 这样可以得到文件名,我想要的是完整路径
我尝试过使用`filepath.Dir()`,但它没有起作用。
<details>
<summary>英文:</summary>
I been searching around and can not find a way to get the full file path in Go . I have a regular html form and then I try to get all the information in the backend
<form method="post" enctype="multipart/form-data" action="/uploads">
<p><input type="file" name="my file" id="my file"></p>
<p>
<input type="submit" value="Submit">
</p>
func upload() {
f,h,err := r.FormFile("my file")
if err != nil {
log.Println(err)
http.Error(w,"Error Uploading",http.StatusInternalServerError)
return
}
defer f.Close()
println(h.Filename)
}
// This gets me the name of the file, I would like the full path of it
I have tried **file path.dir()** but that does not do anything
</details>
# 答案1
**得分**: 11
这是一个示例:
```go
package main
import (
"fmt"
"path/filepath"
)
func main() {
abs,err := filepath.Abs("./hello.go")
if err == nil {
fmt.Println("绝对路径:", abs)
}
}
英文:
here is an example:
package main
import (
"fmt"
"path/filepath"
)
func main() {
abs,err := filepath.Abs("./hello.go")
if err == nil {
fmt.Println("Absolute:", abs)
}
}
答案2
得分: 4
据我所知,你无法从代码中的f
值获取文件路径。因为文件数据尚未存储在磁盘中。
如果你想将文件存储到路径中,可以按照以下方式进行操作:
f, h, err := r.FormFile("myfile")
if err != nil {
log.Println("err:", err)
http.Error(w, "Error Uploading", http.StatusInternalServerError)
return
}
defer f.Close()
fmt.Println("filename:", h.Filename)
bytes, err := ioutil.ReadAll(f)
if err != nil {
fmt.Println(err)
}
filepath := "./aa" //设置你的文件名和文件路径
err = ioutil.WriteFile("aa", bytes, 0777)
if err != nil {
fmt.Println(err)
}
请注意,这只是将文件存储到指定路径的示例代码。你需要根据实际需求修改文件路径和文件名。
英文:
As far as I know, you cannot get the filepath form the f
value in your code. Because the file data is not stored in disk yet.
And you want to store the file to a path, you can do it this way.
f,h,err := r.FormFile("myfile")
if err != nil{
log.Println("err: ",err)
http.Error(w,"Error Uploading",http.StatusInternalServerError)
return
}
defer f.Close()
fmt.Println("filename: ",h.Filename)
bytes, err := ioutil.ReadAll(f)
if err != nil {
fmt.Println(err)
}
filepath := "./aa" //set your filename and filepath
err = ioutil.WriteFile("aa", bytes, 0777)
if err != nil {
fmt.Println(err)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论