Uploading to google cloud storage with Node.js

后端 未结 1 1014
感情败类
感情败类 2021-01-25 01:12

Struggling with Node.js and Google cloud. I am trying to upload a file to a bucket in Google Cloud Storage. Basically I am using the code in this answer: https://stackoverflow.c

相关标签:
1条回答
  • 2021-01-25 02:04

    The authentication of the storage should look like this:

    const storage = new Storage({
        apiKey: "YOUR_API_KEY",
        authDomain: "YOUR_AUTH_DOMAIN",
        databaseURL: "YOUR_DATABASE_URL",
        projectId: "YOUR_PROJECT_ID",
        storageBucket: "YOUR_STORAGE_BUCKET",
        messagingSenderId: "YOUR_MESSAGE_SENDER_ID"
    });
    

    Also working with multipart looks different than with local files. So the code for uploading would be:

                const fileName = 'file_name.extension";
    
                const fileUpload = bucket.file(fileName);
    
                const uploadStream = fileUpload.createWriteStream({
                    metadata: {
                        contentType: file.mimetype
                    }
                });
    
    
                uploadStream.on('error', (err) => {
                    console.log(err);
                    return;
                });
    
                uploadStream.on('finish', () => {
                    console.log('Upload success');
                });
    
                uploadStream.end(file.buffer);
    

    Lastly, bucketName shouldn't contain gs:// - it should look like this: project_id.appspot.com.

    Ps. Uploading mimetype was handled with busboy in the code above.

    0 讨论(0)
提交回复
热议问题