英文:
Golang os.Open can I use form file along with it for dynamic files
问题
这是我第一次使用Os.Open,我想知道是否可以用它来处理动态图片(即不同目录下的图片),还是每次都必须输入完整路径?例如,在我的FormFile中:
func ExampleFunc(w http.ResponseWriter, t *http.Request) {
t.ParseForm()
f, h, err := t.FormFile("file")
if err != nil {
print(err)
}
os.Open(h.Filename)
}
上面的函数给我返回一个错误,说找不到文件或目录,但是如果我在那里输入完整路径,比如:
os.Open("/Home/myfiles/Documents/pictures/horse_riding.png")
那么图片就能打开。有没有办法动态获取图片路径并将其插入到os.Open中?我有一个FormFile,可以获取有关传入文件的信息,但没有完整路径。
英文:
This is my first time using Os.Open and I was wondering can I use that for dynamic images (Images found in different directories) or do I have to put the full path every single time ? For instance in my FormFile
func ExampleFunc(w http.ResponseWriter, t *http.Request) {
t.ParseForm()
f, h, err := t.FormFile("file")
if err != nil {
print(err) }
os.Open(h.Filename)
}
The function above gives me an error no such file or directory found however if I put the full path in there such as
os.Open("/Home/myfiles/Documents/pictures/horse_riding.png")
Then the image opens, is there a way of dynamically get the Image path and inserting that in os.Open ? I do have a FormFile that gets information about the incoming file but not the full path .
答案1
得分: 1
在文件服务器(例如这个),你应该将root_folder
与从表单中获取的文件/路径连接起来。
filepath := path.Join((root_folder), h.Filename)
这样,你打开的文件将位于特定的根文件夹中,而不是系统上的任何文件(这样做是不安全的)。
英文:
In a file server (such as this one), you are suppose to concatenate a root_folder
to the file/path you get from your form.
filepath := path.Join((root_folder), h.Filename)
That way, you open files which are within a certain root folder, instead of any file on your system (which is not secure at all).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论