I have a folder on my node server called /pictures/renamed
. In it, I'm trying to save an image and it does successfully save it however it doesn't display anything except a message that says "It appears that we don't support this file format". I changed the image extension to jpeg, jpg and png but the image still doesnt display. Why is this happening?
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}`));
CodePudding user response:
That's because the response is an html document (telling you that you are redirected) rather than actual jpg data.
It looks something like this in a text editor:
<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>
So, what you saved was not a valid photo file.
Referring to https://github.com/follow-redirects/follow-redirects, I ran npm install follow-redirects
then replaced const https = require('https')
with const { https } = require('follow-redirects')
in the js file, and then I could get the jpg.