Show image immediately after upload in sailsjs

送分小仙女□ 提交于 2019-12-04 14:22:37
bredikhin

Sails uses assets folder to store mainly the assets that are supposed to be precompiled and/or published, e.g. scripts, styles and minor images (icons, etc.). For images it means in most of the cases that upon sails lift they are being copied (including directory structure and symlinks) from ./assets folder to ./.tmp/public, which becomes publicly accessible.

So, the short answer to the question is: in order to become immediately accessible the images should be copied to ./.tmp/public/posts (not to ./assets/posts).

On the other hand, ./.tmp folder is being rewritten during sails lift, and you probably don't want your uploaded images to disappear whenever the application restarts, so it makes sense to upload the images in a completely different folder, let's say ./attachments/posts or whatnot, which in its turn needs to be symlinked from ./.tmp/public/images/posts after the Sails are lifted. For example, in your config/bootstrap.js you can put something like

var fs = require('fs')
  , path = require('path');

module.exports.bootstrap = function (cb) {
  // Whatever else you want to bootstrap...

  var postsSource = path.join(process.cwd(), 'attachments/posts')
    , postsDest = path.join(process.cwd(), '.tmp/public/images/posts');

  fs.symlink(postsSource, postsDest, function(err) {
    cb(err);
  });
};

You can use synchronous version of fs.symlink or async to create multiple links.

Update for windows guys

var sys = require('sys');
var exec = require('child_process').exec;
exec('mklink /j '+postsDest+' '+postsSource , function(err, stdout, stderr){
    cb(err);
});

And, of course, even better way would be uploading the images directly to a CDN/storage service (Amazon S3, etc.) and just generating corresponding URLs to access them.

An alternative, which is OS agnostic, is to change the grunt-clean task (in /tasks/config/clean.js) to specify which folders to clean in your .tmp/public. See example below. In my case, I created a folder "uploads" in .tmp/public, and it does not get deleted.

grunt.config.set('clean', {
    dev: ['.tmp/public/fonts/**','.tmp/public/images/**','.tmp/public/js/**','.tmp/public/js/**','.tmp/public/styles/**','.tmp/public/*.*'],
    build: ['www']
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!