Domanda

This is really more of a "using what method" than a "how-to" question. I am creating a site in NodeJS with Express. So, each user has the ability to upload a profile picture, and my concern is how to route requests for these images. A couple of questions I have are:

  • Can I use express.static() to serve a default file if a valid one isn't specified? If not, am I going to have to specify a GET route for /img/profileand handle the FS querying there?

  • How can I find the correct image if multiple file extensions are allowed? (I originally just removed the file extension and they appeared in img tags anyway, is that okay?)

  • I am currently naming all pictures after their user's name. Looking ahead into the future (for apps I may have to scale), what are normal naming conventions for static user content? Are most stored with a UUID referencing the content in the database?

  • What else should I take into consideration that I may not have accounted for yet?

È stato utile?

Soluzione

First question:

At present, I'd recommend storing your images in a predictable location that can be inferred from some combination of columns or fields in your database entries. One of those fields or columns would be a filename (accounts for different extensions). Then, if they haven't uploaded an image, you just lay down in your view code a reference to the generic "has not set an image" file.

express.static obviously can server static files, but it currently doesn't have a way to serve some other file if the one you wanted isn't there. Because this sounded like fun, I made some modifications to static to support what you request and submitted a couple of pull requests (the feature touched 2 different modules):

I don't know if those will get included in the project, but if you want to see my forks that have these changes, they are here:

If this went through, you would mount a static at the root of your profile image files:

app.use(static('<profile image files root>', { fallback: 'anon.jpg'}))

Second question

I generally store the extension in my DB, then when I load the image, I have the correct extension to put into the src attribute on the img tag.

Third question

If you can guarantee unique names, then using those would work. I prefer using the DB id or a UUID as you suggest. It's less intuitive when scanning all the image uploads, but I rarely find myself doing that. I'm usually hunting for a specific image, and I can look up the identifier for that as needed.

Fourth question

You may end up storing the static content outside your app server (e.g. on S3). If that happens, then of course static won't help you.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top