我的资产文件夹:
assets
| images
| media
| book
| pictures
我想在上面的路径中上传图片时创建新书,但是当我尝试在视图中显示此图像时,图像无法显示且也没有错误。
我的代码是:
//BookController
create: function (request, response, next) {
var title = request.body.title;
var subject = request.body.subject;
var brief = request.body.brief;
var author = request.body.author;
var origin_pic_name = null;
request.file('pic').upload({
dirname: '../../assets/images/media/book/pictures/',
},function (err, file) {
if(err) console.log(err);
origin_pic_name = file[0]['fd'].split('\\').reverse()[0] ;
Book.create({title:title,subject:subject,brief:brief,author:author,pic:origin_pic_name}).exec(function (err) {
if(err) response.end(500, {error: 'Database Error'});
response.redirect('/');
});
});},
index : function (request, response, next) {
Book.find({}).exec(function (err, books) {
if(err) response.end(500, {error: 'Database Error'});
response.view('book/index', {books:books});
});},
//my index.ejs
<ol>
<% books.forEach(function (value) {%>
<h3><li> <%= value.title %></li></h3>
<ul><%= value.author %></ul>
<ul><%= value.subject %></ul>
<ul><%= value.brief %></ul>
<ul><img src="/images/media/book/pictures/<%= value.pic %>"/></ul>
<% })%>
</ol>
谢谢
答案 0 :(得分:2)
开箱即用,帆在升降过程中缓存资产。为了解决这个问题,对于文件上传,您可以更改控制器,以便在上传后立即复制文件。
以下是您可以使用当前控制器执行此操作的示例。您可能需要编辑目录字符串以满足您的需要。
// BookController
create: function (request, response, next) {
var title = request.body.title;
var subject = request.body.subject;
var brief = request.body.brief;
var author = request.body.author;
var origin_pic_name = null;
request.file('pic').upload({
dirname: '../../assets/images/media/book/pictures/',
},function (err, file) {
if(err) console.log(err);
origin_pic_name = file[0]['fd'].split('\\').reverse()[0];
// Variable to hold the current directory
var currentDir = '../../assets/images/media/book/pictures/' + origin_pic_name;
// Variable to hold the temp directory
var tempDir = '.tmp/public/images/media/book/pictures/' + origin_pic_name;
// copy the image from the current directory to the temp to the temp folder
fs.createReadStream(currentDir).pipe(fs.createWriteStream(tempDir));
Book.create({title:title,subject:subject,brief:brief,author:author,pic:origin_pic_name}).exec(function (err) {
if(err) response.end(500, {error: 'Database Error'});
response.redirect('/');
});
});
},
答案 1 :(得分:1)
将图像上传到Sails时需要非常小心:
Grunt正在关注某些文件夹中的更改,包括assets
目录和子目录。但这只能在“发展”环境中实现(激活,tbh)。
images/
目录。skipper
将图片保存在那里。写一个mediaController
,它会捕获/images/media/book/:name
等路线,并会尝试找到并发送文件:
// MediaController.js
var fs = require('fs');
var path = require('path');
module.exports = {
get : function(req, res){
var filepath = req.name.slice(1,req.name.length);
// remove this Sync to an Async
if(fs.existsSync(path.resolve(filepath))){
return res.sendfile(filepath);
} else {
return res.notFound();
}
}
}
//Routes.js
'get /images/books/:name' : 'MediaController.get'
fs
。好DO Spaces
,例如......