2

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!!

Secco Jones
  • 163
  • 5
  • 16

1 Answers1

1

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.

chenglou
  • 3,640
  • 2
  • 25
  • 33
  • Ok, thanks for that. But my question was about showing images in the jade template. See EDIT above. – Secco Jones Sep 04 '12 at 00:05
  • Well yeah, req.files must show the "public" part, or else it'd be unusable elsewhere in your app. You can simply refer to the actual url directly in Jade: `src = '/images/imagename.jpg'`. I'll add that to the answer. – chenglou Sep 04 '12 at 00:11
  • The issue is that the file name is coming from an upload form. I need to get the right path from that. – Secco Jones Sep 04 '12 at 00:26
  • SOLVED thanks to this tutorial http://www.hacksparrow.com/handle-file-uploads-in-express-node-js.html. Thanks everybody! – Secco Jones Sep 04 '12 at 08:22