Express image upload and view in jade

旧城冷巷雨未停 提交于 2019-12-12 09:59:45

问题


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


回答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.



来源:https://stackoverflow.com/questions/12251302/express-image-upload-and-view-in-jade

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!