MWN
MWN

Reputation: 387

unable to display image from static folder in node js

New to Node.js and trying to display image from static folder using

http://localhost:3000/uploads/animal.jpg

but I cannot display it and receives error Cannot GET /uploads/C6MGiE-1528523813517.jpg and when I checked in uploads folder. The image was uploaded successfully. Images are being uploaded through Postman

app.ts

import cors from "cors";
import express from "express";
import mongoose from "mongoose";
import path from "path";
import mediaUploadRoute from "./routes/media-upload.route";

app.use('/api/uploads', mediaUploadRoute);

const app = express();
app.use(express.json());
app.use(cors());

const directory: string = path.join(__dirname, '/uploads/')
app.use(express.static(directory))

media-upload.route.ts

import express from "express";

// mediaFiles is a service that uses multer to host the images to the server
import mediaFiles from "../services/media-files";

const router = express.Router();

router.post('/fileInput_icon', mediaFiles.uploadSingle('fileInput_icon'), (req, res) => {
    let file = req.file;
    file.path = file.path.replace(/\\/g, "/")
    res.status(200).send(JSON.stringify(file.path));
})

router.post('/fileInput_image', mediaFiles.uploadSingle('fileInput_image'), (req, res) => {
    let file = req.file;
    file.path = file.path.replace(/\\/g, "/")
    res.status(200).send(JSON.stringify(file.path));
})

export default router;

What would be the reason? I am working on for many days but no success

Update

app.js

// it created public folder in the root of project directory
app.use(express.static('/public'));

in multer

private storage = multer.diskStorage({
        destination: 'public',
        filename: function (req, file, callback) {
            callback(
                null,
                file.originalname.replace(/\.[^/.]+$/, "") + '-' + Date.now() + path.extname(file.originalname))
        }
    })

tried to access via

http://localhost:3000/C6MGiE-1528530542730.jpg

http://localhost:3000/public/C6MGiE-1528530542730.jpg

but all invain :(

Postman gets response "public/C6MGiE-1528530542730.jpg"

Upvotes: 0

Views: 2907

Answers (1)

jfriend00
jfriend00

Reputation: 707158

The problem is that this code:

const directory: string = path.join(__dirname, '/uploads/')
app.use(express.static(directory))

looks in the correct directory, but isn't set up for the right path. So, when you request /uploads/C6MGiE-1528523813517.jpg, it's looking for __dirname + '/uploads/uploads/C6MGiE-1528523813517.jpg' which it doesn't find.

You can fix it by changing the requested image URL to just /C6MGiE-1528523813517.jpg or by changing the server code to:

const directory: string = path.join(__dirname, '/uploads');
app.use('/uploads', express.static(directory));

Upvotes: 4

Related Questions