Node Fastify - 提供位于上传文件夹中的图像
Node Fastify - serve images located in upload folder
当我们导航到
时,使files/images可用
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" });
...
routes/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}
如果未在 FastifyStatic
配置中指定 prefix
,将使用默认值 /
。因此,为了访问您的静态文件,您需要将请求路径从 /properties/images/<your-img.jpg>
更改为 /images/<your-img.jpg>
。
或者,您可以使用自定义前缀,例如 public
,就像他们在 documentation:
中所做的那样
fastify.register(require('fastify-static'), {
root: path.join(__dirname, 'uploads'),
prefix: '/public/',
})
然后用/public/images/<your-img.jpg>
请求它。
当我们导航到
时,使files/images可用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" });
...
routes/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}
如果未在 FastifyStatic
配置中指定 prefix
,将使用默认值 /
。因此,为了访问您的静态文件,您需要将请求路径从 /properties/images/<your-img.jpg>
更改为 /images/<your-img.jpg>
。
或者,您可以使用自定义前缀,例如 public
,就像他们在 documentation:
fastify.register(require('fastify-static'), {
root: path.join(__dirname, 'uploads'),
prefix: '/public/',
})
然后用/public/images/<your-img.jpg>
请求它。