首页 > 解决方案 > Node Fastify - 提供位于上传文件夹中的图像

问题描述

当我们导航到时,使文件/图像可供访问

localhost:8000/properties/files/[image name]

localhost:8000/properties/files/1635843023660-profile.jpg

文件结构

node_modules
src/
uploads/
    1635843023660-profile.jpg
    1635843023668-home.jpg
...
.env
package.json

index.js

import Fastify from "fastify";
import FastifyStatic from "fastify-static";
import path from "path";
import { propertiesRoutes } from "./routes/properties.js";
...
export const fastify = await Fastify({ logger: process.env.LOGGER || true });

const __dirname = path.resolve(path.dirname(""));
fastify.register(FastifyStatic, {
  root: path.join(__dirname, "uploads"),
});
fastify.register(propertiesRoutes, { prefix: "/properties" });
...

路线/properties.js

export const propertiesRoutes = function (fastify, opts, done) {
  ...
  fastify.get("/images/:name", (req, res) => {
    res.sendFile(process.cwd() + "/uploads/" + req.params.name);
  });
  done();
};

截至目前,我得到

{"message":"Route GET:/properties/images/1635843023660-profile.jpg not found","error":"Not Found","statusCode":404}

标签: javascriptnode.jsfastify

解决方案


如果未prefixFastifyStatic配置中指定 a,则将使用默认值/。因此,为了访问您的静态文件,您需要将请求路径从 更改/properties/images/<your-img.jpg>/images/<your-img.jpg>.

public或者,您可以像在文档中那样使用自定义前缀:

fastify.register(require('fastify-static'), {
  root: path.join(__dirname, 'uploads'),
  prefix: '/public/',
})

然后用/public/images/<your-img.jpg>.


推荐阅读