Secco Jones
Secco Jones

Reputation: 163

Express image upload and view in jade

I'm trying to upload an image and show it in express. I configured my app to upload in 'public/images'

  app.use(express.bodyParser({ keepExtensions: true, uploadDir: './public/images' }));

The upload goes great but I can't find how to show uploaded images in my jade template. The image path I get from the req.files object is something like 'public/images/imagename.jpg' but the only way I can see images is in a url like this:

http://localhost:3000/images/imagename.jpg

Is there a way to maybe remove the 'public' parameter from req.files, or are there other solutions?? Thanks everyone!

EDIT:

Ok, thanks for that. But my question was about showing images in the jade template. I added this line:

app.use('/public/images/', express.static(__dirname + '/public/images/'));

and now I can reach files in that directory. But I'm not able to show them in my jade template. When I try this (with foto_path === req.files.image.path):

img(src= #{material.foto_path})

I get this url:

http://localhost:3000/undefinedpublic/images/b1ce29f40ac7692ac62637e42f0f9128.jpgundefined

What are the 'undefined' for?

Thanks!!

Upvotes: 2

Views: 8692

Answers (1)

chenglou
chenglou

Reputation: 3640

You need to know that Express configure your public directory a little bit differently than other traditional servers like Apache. I guess that for displaying static assets, your line looks like this:

app.use(express.static(__dirname + '/public'));

That'll be the only publicly viewable folder in your app. This is why Express find it redundant to add the name of the directory to the url. The url doesn't reflect your actual folder structure.

But req.files does show the actual path so that you can manipulate it in your app, or else it'd be unusable elsewhere. My solution would be to directly refer to src = '/images/imageName.jpg' in Jade. You'd have to pass the actual image name as parameter. Or, you can just strip the "public" part from req and pass it.

Upvotes: 1

Related Questions