Search code examples
node.jsherokumulter

Files uploaded with multer disappears when the heroku server restarts


I am using multer in node.js to upload files (that are coming from a client project based on Angular) to my Heroku server. Everything works fine, but when the Heroku server restarts or goes down all the uploaded files disappears, the URL hits returns 'Not Found'.

This is my code to upload files :

var express = require('express');
var router = express.Router();
var mysql = require('mysql');
var multer = require('multer');
var pool = require('./dbconnection');

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '/app/public/images/postImages/')
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now()+'.jpg')
  }
})

var upload = multer({ storage: storage })


router.post('/postImages', upload.single('image'), function(req, res) {

var userId              = req.body.userId;
var postTitle           = req.body.postTitle;
var postDesc            = req.body.postDesc;
var postLat             = req.body.postLat;
var postLng             = req.body.postLng;
var postMediaType       = req.body.postMediaType;
var postMediaFileName   = req.file.filename;
var postMediaFilePath   = req.file.destination;
var postMediaFileURL    = req.file.path;
postMediaFileURL        = postMediaFileURL.substring(postMediaFileURL.indexOf('images/'), postMediaFileURL.length);

var inserts = [postTitle, postDesc, postLat, postLng, postMediaType, postMediaFileName, postMediaFilePath, postMediaFileURL, userId];
var sql = "INSERT INTO posts (postTitle, postDesc, postLat, postLng, postMediaType, postMediaFileName, postMediaFilePath, postMediaFileURL, userId) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
sql = mysql.format(sql, inserts);
console.log(sql);

pool.getConnection(function(err, connection) {
    connection.query(sql, function(error, results) {
        connection.release();
        res.json(results);
        if(error) throw error;
    });
});
});

module.exports = router;

Tell me what am I missing or what am I doing wrong.


Solution

  • The answer is in your question, it's heroku. after the application restarts only the deployed files will stay on the server.

    I suggest using a remote storage, I recommend 'cloudinary' as a free solution for media storage.

    But if you want to stick with heroku as a storage there is always the option to upgrade.