【问题标题】:Google Cloud Storage - How to Upload content directly from browser (JavaScript)Google Cloud Storage - 如何直接从浏览器上传内容 (JavaScript)
【发布时间】:2020-11-20 18:48:00
【问题描述】:
如何直接从浏览器 (JavaScript) 上传内容到 GC 存储?
是否有一些简单的方法可以使用令牌(在 URL/cookies 中)或类似方法?
注意:不考虑任何中间系统(如 URL 签名者)。我正在寻找一种从 JS 发送请求并在 GC 存储中处理它的方法。
如果不是,您知道不引入太多依赖项和复杂性的最简单解决方案是什么?
【问题讨论】:
标签:
javascript
json
google-cloud-platform
google-cloud-storage
google-cloud-messaging
【解决方案1】:
这很容易。您可以使用 Firebase JavaScript SDK 在网络上执行此操作。
https://firebase.google.com/docs/storage/web/upload-files
文档中的代码
var uploadTask = storageRef.child('images/rivers.jpg').put(file);
// Register three observers:
// 1. 'state_changed' observer, called any time the state changes
// 2. Error observer, called on failure
// 3. Completion observer, called on successful completion
uploadTask.on('state_changed', function(snapshot){
// Observe state change events such as progress, pause, and resume
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED: // or 'paused'
console.log('Upload is paused');
break;
case firebase.storage.TaskState.RUNNING: // or 'running'
console.log('Upload is running');
break;
}
}, function(error) {
// Handle unsuccessful uploads
}, function() {
// Handle successful uploads on complete
// For instance, get the download URL: https://firebasestorage.googleapis.com/...
uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log('File available at', downloadURL);
});
});