1
votes

I have a Google Cloud function that take the screenshot of a url and i need to upload that image to google cloud bucket from google cloud function

I have tried uploading it using the code given below but it does not work and gives error

    /**
     * Responds to any HTTP request.
     *
     * @param {!express:Request} req HTTP request context.
     * @param {!express:Response} res HTTP response context.
     */
    exports.takeScreenshot = (req, res) => {

    const Screenshot = require('url-to-screenshot')
    const Storage = require('@google-cloud/storage')
    const fs = require('fs')
    const bucketName="screenshot_bucket_mujahid"
    new Screenshot('http://ghub.io/')
      .width(800)
      .height(600)
      .capture()
      .then(img =>
        Storage
        .bucket(bucketName)
        .upload(img,"mujahid.jpg"))
        console.log('open example.png')
      })

      let message = req.query.message || req.body.message || 'Hello World!';
      res.status(200).send(message);
       };
2
What is the error returned?Kolban
Function failed on loading user code. Error message: Code in file index.js can't be loaded. Is there a syntax error in your code? Detailed stack trace: /srv/index.js:20 .upload(img,{"Mujahid.jpg"}) ^ SyntaxError: Unexpected token }Mujahid

2 Answers

1
votes

Your code appears to have a syntax error. Instead of:

.then(img =>
        Storage
        .bucket(bucketName)
        .upload(img,"mujahid.jpg"))
        console.log('open example.png')
      })

it might be correct to code:

.then(img =>
   {
     Storage
       .bucket(bucketName)
       .upload(img,"mujahid.jpg");
     console.log('open example.png');
   });
0
votes

Try something like this :

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();
const bucketName = ' something ' // bucket you want to upload to
const fileName = ' some path ' // PATH of the file

await storage.bucket(bucketName).upload(filename, {
gzip: true,
metadata: { 
 cacheControl: 'no-cache'
 },
});

So, be aware that to the upload function, you must pass the whole path of the file you want to upload.

If the upload still does not work, check if you don't have any permission issues in your GCS bucket. Try to make data public and retry to upload. But most likely, if your file is not uploaded and you get no error, something may remain stucked in this portion of code :

new Screenshot('http://ghub.io/')
  .width(800)
  .height(600)
  .capture()