picture do not show in sails.js view

假如想象 提交于 2019-12-04 20:31:52

You need to be very careful when uploading images to Sails:

The Problem

Grunt is watching for changes in some folders, including the assets dir and subdirs. But that is only possible (activacted, tbh) in "Development" enviroment.

The solution

  • Create a images/ dir in your root.
  • When uploading the image, make skipper save the image there.
  • Write a mediaController that will catch routes like /images/media/book/:name and will try to locate and send a file:

    // 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'
    

Advantages

  • You can now restrict the access of images with policies, if you want to!
  • Better handling at image and 100% control over the fs. Good with DO Spaces, for example...

Out of the box, sails caches assets during the sails lift process. To get around this, for file uploads, you can alter your controller to copy the file immediately after upload.

Here is an example of how you might do that with your current controller. You may need to edit the directory strings to suit your needs.

// 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('/');
        });
    });
},  
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!