I'm accepting files to be uploaded to my site. So, is it a safe practice to encodeURIComponent the filename? Or should I use escape()? OR is it necessary at all?
You should never use escape
for anything (unless forced to because you're sending information to something that will use unescape
[which it shouldn't]).
Whether you need to use encodeURIComponent
depends entirely on whether you're going to use the filename directly as a URI component¹. If you are, yes, you should use it. If you aren't, no, you probably shouldn't.
¹ for instance, as a query string parameter when you're creating the query string manually rather than via URLSearchParams
(which is generally better practice)
encodeURIComponent
takes a string and escapes it to make it safe to insert into a URI, typically used for query string data.
If you are inserting a string into a URI then you can use it, but should probably use URLSearchParams
to construct the whole query string instead.
If you aren't inserting a string into a URI then you probably should not use it.
escape
is deprecated and should not be used. It doesn't work property with Unicode.
Considerations for accepting files are typically more along the lines of "Will this accidentally overwrite an existing file?" and "Are the characters in this filename allowed by my filesystem?".
Some people prefer to generate a completely new file name (e.g. with a guid library) to ensure it is safe. You could store the original name in a database (at which point your escaping should be handled by parametrised queries).