Is it possible to get the path where files sent from forms are saved in go?

Viewed 54

I am having a problem when I want to work with files sent to a web server in golang, the first thing I do is have all the files sent, with the following code:

r.ParseMultipartForm(0)

files := r.MultipartForm.File

for file := range files {
    file, header, error := r.FormFile(file)

    if error != nil {
      log.Print(error)
    }
}

The r variable is the value of *http.Request. So far I think so far everything is going well. But, according to the official documentation of ParseMultipartForm:

The whole request body is parsed and up to a total of maxMemory bytes of its file parts are stored in memory, with the remainder stored on disk in temporary files.

In other words, the files are saved on the server. Is it possible to obtain the path where they are saved? I don't think copying the files is a good idea because that would take up twice as much disk space for each request. Am I missing something? Or am I misunderstanding the documentation?

Just to clarify, I would like to get the path where they are saved ( for example: "/tmp/file.jpg"). I hope you can help me, thanks in advance.

1 Answers

First and foremost, this is incorrect:

I don't think copying the files is a good idea because that would take up twice as much disk space for each request.

Note the word "temporary" in your quoted documentation. Any temporary files that may exist will be deleted unless you do copy them someplace permanent.

Regarding getting their paths, you can't do this, and you don't need to. Note the rest of your quoted documentation:

The whole request body is parsed and up to a total of maxMemory bytes of its file parts are stored in memory

For many files, there is no file on disk. The file only lives in memory. It's only the stuff that doesn't fit in memory that ends up in one (or more) temporary files. Those files are useless to you, they are an implementation detail that you cannot depend on.

Your are meant to use the provided file handle and FileHeader object returned by FormFile to interact with the uploaded file.

Related