无法在节点js中显示静态文件夹中的图像

时间:2018-06-09 06:30:02

标签: node.js image static

Node.js新手并尝试使用

显示静态文件夹中的图像

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

但是当我在Cannot GET /uploads/C6MGiE-1528523813517.jpg文件夹中签到时,我无法显示它并收到错误uploads。图像已成功上传。正在通过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))
  

媒体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;

原因是什么?我正在工作很多天但没有成功

更新

  

app.js

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

中的

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

尝试通过

访问

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

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

但是所有人都拥有:(

Postman获得回复"public/C6MGiE-1528530542730.jpg"

1 个答案:

答案 0 :(得分:2)

问题是这段代码:

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

查找正确的目录,但未设置正确的路径。因此,当您请求/uploads/C6MGiE-1528523813517.jpg时,它正在寻找它找不到的__dirname + '/uploads/uploads/C6MGiE-1528523813517.jpg'

您可以通过将请求的图片网址更改为/C6MGiE-1528523813517.jpg或将服务器代码更改为:

来解决此问题。
const directory: string = path.join(__dirname, '/uploads');
app.use('/uploads', express.static(directory));