Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can not see the image I just uploaded [sails.js]

Tags:

image

sails.js

I have this to upload photos:

module.exports = function (req, image, url, callback) {
var filename = (Math.floor((Math.random() * 100000000000) + 1)) + ".png";
req.file(image).upload({
  dirname: '../../assets/images' + url
,
  saveAs: function(file, cb) {
    cb(null, filename);
  }
}, function(error, uploadedFiles) {
  return callback(null, "http://" + req.headers.host + "/images" + url + filename)
});

}

And it returns an url like this: http://localhost:1349/images/dependent/photos/30363010266.png

I can see that my photo is uploaded in project folder because I see it physically. But the URL do not work and has appeared not found error.

If I restart server, the URL works fine.

Thanks!

like image 527
oihi08 Avatar asked Jan 08 '23 15:01

oihi08


1 Answers

As @Eugene Obrezkov pointed out, your issue is related to where you are uploading your images and the grunt task runner. All the assets are copied from that folder (/assets) to the .tmp, and changes are watched by the grunt task runner, but that doesn't include new image files(If you are to an empty folder in the assets folder, in your case to the image folder). So the solution is quite easy, you must upload directly to the .tmp folder, ideally to .tmp/public/uploads/year/month/, you can choose your path as you see fit. Now there is a caveat with this approach, and it is that there is a grunt task that clears the contents of the .tmp folder on sails lift, so you will get the opposite effect, now to avoid this is quite easy too, you must edit the clean.js task to delete specific folders, to avoid deleting your uploads folder.

Go to to your project folders tasks/config/clean.js, and replace what's in there for this code, or modify it as you need.

module.exports = function(grunt) {
    grunt.config.set('clean', {
      dev: [
        getFolderPath('fonts/**'),
        getFolderPath('images/**'),
        getFolderPath('images/**'),
        getFolderPath('js/**'),
        getFolderPath('styles/**'),
        getFolderPath('*.*')
      ],
      build: ['www']
    });

    grunt.loadNpmTasks('grunt-contrib-clean');
};

function getFolderPath(folderName){
  return '.tmp/public/' + folderName;
}

Now your uploads will appear immediately to your end-user without restart, and restarts won't delete those uploads. Just make sure the .tmp/public/uploads/ path exist before trying to upload, or use mkdir to create it via code if not found.

There are other solutions, like making sure there is at least a file in the folder you are uploading to when the server starts, or using symlinks, but i think this is a cleaner approach. You can check those options here:

Image not showing immediately after uploading in sails.js

like image 158
Lu Roman Avatar answered Feb 15 '23 10:02

Lu Roman