我的 Node 服务器上有一个名为 /pictures/renamed
的文件夹。在其中,我尝试保存图像,它确实成功保存了它,但是除了一条消息“看来我们不支持此文件格式”之外,它没有显示任何内容。我将图像扩展名更改为 jpeg、jpg 和 png,但图像仍然不显示。为什么会发生这种情况?
const express = require('express');
const bodyParser = require('body-parser')
const app = express();
const https = require('https');
const fs = require('fs');
const cors = require('cors');
const pathh = require('path')
//Setting up the cors config
app.use(cors());
//BodyParser middleware
app.use(express.json());
function download(){
const url = 'https://unsplash.com/photos/3aqiY4t1qxM/download?ixid=MnwxMjA3fDB8MXxhbGx8Mnx8fHx8fDJ8fDE2NTY3Njg2Mzc&force=true'
const path = pathh.resolve("./pictures/renamed/", 'imageWorld.jpg')
const fileStream = fs.createWriteStream(path)
https.get(url,(res)=>{
res.pipe(fileStream)
fileStream.on('finish',()=>{
fileStream.close()
})
})
}
download();
//Serve static files if in production
if(process.env.NODE_ENV === 'production'){
//Set static folder
app.use(express.static('client/build'));
app.get('*', (req, res) =>{
res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
});
}
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
最佳答案
这是因为响应是一个 html 文档(告诉您已重定向)而不是实际的 jpg 数据。
在文本编辑器中看起来像这样:
<html><body>You are being <a href="https://images.unsplash.com/photo-1656712193135-ef15d7ea27d6?ixlib=rb-1.2.1&dl=georgie-cobbs-3aqiY4t1qxM-unsplash.jpg&q=80&fm=jpg&crop=entropy&cs=tinysrgb">redirected</a>.</body></html>
因此,您保存的不是有效的照片文件。
引用https://github.com/follow-redirects/follow-redirects ,我跑了npm install follow-redirects
然后替换const https = require('https')
与 const { https } = require('follow-redirects')
在js文件中,然后我可以得到jpg。
关于javascript - Node 服务器下载图片成功但不显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72840124/