javascript - Node 服务器下载图片成功但不显示

标签 javascript node.js fs

我的 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&amp;dl=georgie-cobbs-3aqiY4t1qxM-unsplash.jpg&amp;q=80&amp;fm=jpg&amp;crop=entropy&amp;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/

相关文章:

javascript - 在 Electron 中打开本地文件并在 wavesurfer.js 中渲染

javascript - 在 Node 脚本中,如何监视文件的更改并获取更新的内容?

javascript - 如何将 Javascript 数组字符串化以存储在 localStorage 中

javascript - 如何使用 selenium python 从动态网站检索所有链接

javascript - 是否有可能通过 http 获取用户位置,或者 https 是唯一的解决方案?

Node.js:在 MongoDb 中使用 Promises

node.js - windows中的node js无法在js中运行Hello World程序

node.js - 如何在node.js/socket.io中使用removeListener来防止多次触发函数

javascript - node.js 调用 perl 脚本并获取标准输出

javascript - Promise 的返回值不稳定