Golang的os.Open函数可以与表单文件一起使用来处理动态文件吗?

huangapple go评论85阅读模式
英文:

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

huangapple
  • 本文由 发表于 2017年1月14日 13:09:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/41646985.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定