我正在嘗試根據用戶輸入的引數從我的專案中的“影像”檔案中提供影像。
例如,
https://localhost:3000/images?fileName=burger
應該在瀏覽器上顯示影像
有誰知道我該怎么做?
我的結構如下:
圖片 ---burger.jpg src ---index.ts
我試圖這樣做,但由于某種原因它不起作用
app.use('/images', express.static('images'));
if(req.query.fileName === "burger"){
res.sendFile("burger.jpg" , {root: path.join("./images")});
}
uj5u.com熱心網友回復:
根據您的代碼,如果您的檔案結構如下。您的代碼將完美運行。確保您在 express.static() 下設定了提供靜態檔案的路徑,并注意您的傳入查詢值與您需要獲取的檔案完全匹配,包括案例。這應該可以解決問題,謝謝!
File Structure:
images
--- burger.jpg
index.js
import express from 'express';
import path from 'path'
const app = express();
const PORT = process.env.PORT || 5000;
app.use('/images', express.static('images'));
app.get('/images', (req, res) => {
if(req.query.filename === 'rocket'){
res.sendFile("rocket.jpg" , {root: path.join("./images")});
})
app.listen(PORT, () => {
console.log('Server is up and running on PORT: ${PORT}');
})
您還可以通過洗掉該中間件來避免所有這些大驚小怪,而是在發送檔案時提供絕對路徑。例如:
app.get('/images', (req, res) => {
if(req.query.filename === 'rocket'){
res.sendFile(path.join(__dirname, "images/Rocket.jpg"));
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/526663.html
