Show image immediately after upload in sailsjs

自古美人都是妖i 提交于 2020-02-20 10:54:56

问题


I have form with upload field. After searching for a while, I just put uploaded files to folder ./assets/posts and it worked correctly.

In my app, when submit done, it should be reload current url and show new uploaded image. But it didn't. My sails app use linker to manage assets. So after 3 or 4 times I try to reload the page, image is showed.

How to show image immediately when I submit done? Thanks a lot!


回答1:


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.




回答2:


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']
});


来源:https://stackoverflow.com/questions/21128144/show-image-immediately-after-upload-in-sailsjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!