0

I am new to node. I have been digging around trying to find out how to route an incoming image that I am getting from google drives api. I've tried downloading it but it takes to long. I want to be able to send it to the client as soon as i get it. It's probably simple but all I want to do is save it to a png file. . ant help would be greatly appreciated.

 app.get("/img", function(req,res){

 https.get(url,function(resp){
   console.log(resp.statusCode);
  console.log(resp.headers['content-type']);
   resp.on("data", function(chunk){
   // I am getting the image raw data  
 .pipe(fs.createWriteStream("public/images/test.png")); 
Josh Allred
  • 15
  • 1
  • 7

1 Answers1

0

You can pipe the incoming data directly to a file:

resp.pipe(fs.createWriteStream("public/images/test.png"))

Youre code will become:

app.get("/img", function(req,res){
 https.get(url,function(resp){
        console.log(resp.statusCode);
        console.log(resp.headers['content-type']);
        resp.pipe(fs.createWriteStream("public/images/test.png"));
    });
});
ToTheMax
  • 981
  • 8
  • 18
  • This is putting it in the file but its the entire response. How could I tap into the image only? – Josh Allred Apr 15 '20 at 01:02
  • what content-type is the response then? It should be something like image/jpeg – ToTheMax Apr 15 '20 at 09:33
  • text/html; charset=utf-8 – Josh Allred Apr 15 '20 at 11:24
  • Then this URL isn't an image. Make sure the URL is a direct link to the image, try for example your profile picture: https://lh6.googleusercontent.com/-poGft7zXvuc/AAAAAAAAAAI/AAAAAAAAAAA/AAKWJJOyNllQGCbae8U6WdfKBK4reAVqAA/photo.jpg – ToTheMax Apr 15 '20 at 12:01
  • i'm using the shareable link provided from google-drive. If I use resp.on("data", function(chunk){ res.write(chunk); }); I am able to get the image on my page. I just don't know how to direct it to the file. – Josh Allred Apr 15 '20 at 12:23
  • That's because a shareable link isn't a direct link to the image but to a webpage. Can you try to put `&export=download` at the end of the link? – ToTheMax Apr 15 '20 at 12:34
  • You should follow the redirect, check: https://www.npmjs.com/package/follow-redirects – ToTheMax Apr 16 '20 at 12:46
  • 1
    I was able to access it using the download you provided and also with "https://drive.google.com/uc?id="+fileId. It was responding with 302 redirect I was able to tap into it using resp.headers.location, (https://stackoverflow.com/questions/16687618/how-do-i-get-the-redirected-url-from-the-nodejs-request-module) assigning it to a variable and immediately sending another get request. Everything is now working. I have been on this forever. Thank you for your time and help! – Josh Allred Apr 16 '20 at 14:02