Report this

What is the reason for this report?

Upload Images to DO Volume attached to Droplet

Posted on January 5, 2021

I’m currently building a blog using a MEVN stack. My Kubernetes cluster runs on DO (otherwise I wouldn’t be here).

I’ve been trying to figure out how exactly to get my images into this volume I created and I have no idea how to do it. I also don’t know how I would retrieve the images as well.

I’ll show you guys my node backend to show you guys what I’m doing so far.

const express = require('express');
const path = require('path');
const Posts = require('../db/models/post');
const router = express.Router();
const multer = require('multer');

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './uploads/');
  },
  filename: function (req, file, cb) {
    cb(null, file.originalname)
  }
});

const fileFilter = (req, file, cb) => {
  if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
    cb(null, true);
  }
  else {
    cb(null, false);
  }
};

const upload = multer({
  storage: storage,
  limit: {
    fileSize: 1024 * 1024 * 5
  },
  fileFilter: fileFilter
});
router.post("/createPost",upload.single('img'), (req, res) => {
  let currDate = new Date().toISOString();
  let post = req.body;
  post.postId = Math.floor((Math.random() * 9999999) + 1000000);
  post.date = currDate;
  post.img = req.file.path;
  post = new Posts(post);
  console.log(req.body);

  post.save().then(() => {
    res.status(200).send("Post has been uploaded");
  })
    .catch(() => {
      res.status(400).send("unable to post");
    })

});

Locally all my files will save to /uploads/ but how do I configure it to save to my volume and then how do I get the images from my volume as well?



This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Hi there @astronik,

What I would personally do in this case is to mount the volume to the uploads directory.

That way you will not have to change your application in any way, so when you upload images they would again be uploaded to the uploads folder and as the volume is mounted to that uploads directory, the images will be saved on a persistent volume.

Hope that this helps.

Regards, Bobby

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.