user1136342
user1136342

Reputation: 4941

How can I find the current filename from a file object?

How do I find the current filename, if all I have is the file object?

The file is one that a user uploads, and I want to find its name but, if I use file_object.path, it gives the name that the file was created as, rather than the current name.

That produced a name that seemed like a random bunch of numbers and letters; The sample file was a certificate I created which is the type of file the user will upload, so I want to make sure I show the current file name so it's not confusing.

Upvotes: 0

Views: 532

Answers (1)

Mark Paine
Mark Paine

Reputation: 1894

The short answer is "you can't".

To understand why, in a typical filesystem a file is just a node (or in Unix/Linux-speak, an inode) which can be referred to by many links, and I'm not talking about symlinks.

For example:

$ echo "i am foo" > foo
$ cat foo
i am foo
$ ln foo bar    # this is a hard link, not a symlink
$ rm foo
$ cat bar
i am foo
$ rm bar
$ cat bar
cat: bar: No such file or directory
$ cat foo
cat: foo: No such file or directory

In fact, if you look at the Ruby documentation for File::Stat...

http://www.ruby-doc.org/core-1.9.3/File/Stat.html

...you'll see that there is a method nlink that returns the number of hard links to the file. You'll also see that there is a method inspect which returns attributes for the file, but no names.

Upvotes: 2

Related Questions