I am using sails Js and Mongo DB in my application. I upload an image and content for a blog post. I save it in images folder.I save the file destination and content to my mongodb. using the file destination, I want to display the content and image in my HTML page. Content is being displayed but image is not getting displayed. controller:
savepost:function(req,res){
var uploadFile=req.file("image")
uploadFile.upload({maxBytes:1000000,dirname:'../../assets/images'}, function onUploadComplete(err, files) {
// Files will be uploaded to ./assets/images
// Access it via localhost:1337/images/file-name
if (err) return res.serverError(err);
// IF ERROR Return and send 500 error
filename=files[0].fd;
var content=req.body.content;
var title=req.body.title;
Cyberblog.create({title:title,content:content,date:date,filename:filename,}).exec(function(err){
if(err){
console.log(err);
message="content not saved";
console.log(message)
res.redirect('/newpost');
}
else{
var start=filename.lastIndexOf('\\');
fd="images/"+filename.substring(start+1)
post={
title:title,
content:content,
fd:fd,
}
res.view('pages/blog/blog',{post:post})
console.log("succesfully saved")}
}); }); },
Html file:
<div class="container">
<div class="row align-items-stretch retro-layout-2">
<div class="col-md-4">
<a href="single.html" class="h-entry mb-30 v-height gradient" style="background-image:url(<%= post.fd %>);">
<div class="text">
<h2><%= post.title %></h2>
</div>
</a>
</div>
</div>
I am unable to figure out if this is correct or not <%= post.fd %>. Please help me.
The /assets/images
directory is moved to the .tmp/public/images
when you run sails lift
if you are using tasks with Grunt.
Then, you need to check the uploadedFile.fd value to verify the right directory where your file is stored because your public directory is .tmp/public
, then to get images as localhost:1337/images/my-image.png
it should be in the local directory as .tmp/public/images/my-image.png
.
When that is resolved, you could use the relative path to access the file via URL or something like that in the controller:
const url = require('url')
post.imageUrl = url.resolve(sails.config.custom.baseUrl, post.fd)
And then, in the view, use this value to show the image:
<a href="single.html" class="h-entry mb-30 v-height gradient" style="background-image:url(<%= post.imageUrl %>);">