我在我的应用程序中使用sails Js和Mongo DB。我上传了博客文章的图片和内容。我将其保存在images文件夹中,并将文件目标和内容保存到mongodb中。使用文件目标,我想在HTML页面中显示内容和图像。正在显示内容,但未显示图像。 控制器:
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文件:
<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>
我无法弄清楚这是否正确。<%= post.fd%>。请帮助我。
答案 0 :(得分:0)
如果通过Grunt使用任务,则在运行/assets/images
时.tmp/public/images
目录将移至sails lift
。
然后,由于公用目录为.tmp/public
,因此需要检查uploadFile.fd值以验证文件存储的正确目录,然后以localhost:1337/images/my-image.png
的形式获取映像,该映像应位于本地目录为.tmp/public/images/my-image.png
。
解决该问题后,您可以使用相对路径通过URL或控制器中的类似内容访问文件:
const url = require('url')
post.imageUrl = url.resolve(sails.config.custom.baseUrl, post.fd)
然后,在视图中,使用此值显示图像:
<a href="single.html" class="h-entry mb-30 v-height gradient" style="background-image:url(<%= post.imageUrl %>);">