我一直在四处寻找,但找不到在 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>
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)
}
Run Code Online (Sandbox Code Playgroud)
// 这让我得到文件的名称,我想要它的完整路径
我试过文件 path.dir() 但这没有做任何事情
这是一个例子:
package main
import (
"fmt"
"path/filepath"
)
func main() {
abs,err := filepath.Abs("./hello.go")
if err == nil {
fmt.Println("Absolute:", abs)
}
}
Run Code Online (Sandbox Code Playgroud)
小智 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" //set your filename and filepath
err = ioutil.WriteFile("aa", bytes, 0777)
if err != nil {
fmt.Println(err)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8924 次 |
| 最近记录: |