Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· OpenAIAi2 WildChat-4.8M (AI2)

code nodejs connect and upload image to google cloud storage bucket

  1. User

    code nodejs connect and upload image to google cloud storage bucket

  2. Assistant

    To connect and upload an image to a Google Cloud Storage bucket using Node.js, you can use the @google-cloud/storage package. Follow these steps:

    1. Setup:

      • Create a new Google Cloud project.
      • Enable the Cloud Storage API.
      • Create a service account and download the JSON key file.
    2. Install dependencies:

      • Open your terminal and navigate to your project directory.
      • Run the following command to install the @google-cloud/storage package:
        npm install @google-cloud/storage
        
    3. Create a new JavaScript file (e.g., uploadImage.js) and add the following code:

    const { Storage } = require('@google-cloud/storage');
    const path = require('path');
    
    // Replace 'YOUR_PROJECT_ID' with your Google Cloud project ID
    const storage = new Storage({ projectId: 'YOUR_PROJECT_ID', keyFilename: 'path/to/your/keyfile.json' });
    const bucketName = 'your-bucket-name';
    
    async function uploadImageToBucket(imageFile) {
      try {
        const bucket = storage.bucket(bucketName);
        const fileName = path.basename(imageFile);
    
        // Upload the image file to the bucket
        await bucket.upload(imageFile, {
          destination: fileName,
        });
    
        console.log(`Image ${fileName} uploaded to ${bucketName}`);
      } catch (err) {
        console.error('Error uploading image', err);
      }
    }
    
    // Usage example
    const imageFilePath = 'path/to/your/image.jpg';
    uploadImageToBucket(imageFilePath);
    

    Make sure to replace the following variables:

    • YOUR_PROJECT_ID: Replace it with your actual Google Cloud project ID.
    • path/to/your/keyfile.json: Replace it with the path to your service account JSON key file.
    • your-bucket-name: Replace it with the name of your Google Cloud Storage bucket.
    • path/to/your/image.jpg: Replace it with the path to the image you want to upload.
    1. Save the file and run it using the following command:
    node uploadImage.js
    

    This code uploads the specified image file to the specified bucket. If the upload is successful, it will print a success message; otherwise, it will print an error message.