Last active
October 17, 2023 07:50
-
-
Save shaffeeullah/b2b770228761ad8a84d7a2ba61c031c6 to your computer and use it in GitHub Desktop.
Generate signed policy URL for upload via PUT request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async function generateV4SignedPolicy() { | |
// The ID of your GCS bucket | |
const bucketName = 'your-unique-bucket-name'; | |
// The ID of your GCS file | |
const fileName = 'your-file-name'; | |
const bucket = storage.bucket(bucketName); | |
const file = bucket.file(fileName); | |
// These options will allow temporary uploading of a file | |
// through an HTML form. | |
const expires = Date.now() + 10 * 60 * 1000; // 10 minutes | |
const options = { | |
expires, | |
fields: {'x-goog-meta-test': 'data'}, | |
}; | |
// Get a v4 signed policy for uploading file | |
const [response] = await file.generateSignedPostPolicyV4(options); | |
// Create an HTML form with the provided policy | |
let output = `<form action="${response.url}" method="POST" | |
enctype="multipart/form-data">\n`; | |
// Include all fields returned in the HTML form as they're required | |
for (const name of Object.keys(response.fields)) { | |
const value = response.fields[name]; | |
output += ` <input name="${name}" value="${value}" type="hidden"/>\n`; | |
} | |
output += ' <input type="file" name="file"/><br />\n'; | |
output += ' <input type="submit" value="Upload File"/><br />\n'; | |
output += '</form>'; | |
console.log(output); | |
} | |
// Full sample here: | |
// https://github.com/googleapis/nodejs-storage/blob/main/samples/generateV4SignedPolicy.js |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment