javascriptxssencodeuricomponent

Should we enclose filename with encodeURIComponent in Javascript?


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?


Solution

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