gcloud-node - 如何确保通过签名URL上传到Google云端存储的文件是否可公开读取?

时间:2016-05-13 22:52:58

标签: javascript node.js google-cloud-storage google-cloud-platform

我想允许客户端(浏览器中的JavaScript)将文件上传到Google云端存储,这是我目前通过生成signed URLs来完成的。但是,默认情况下,上载的文件是私有的。如何确保通过签名URL上传的文件是公共可读的?

1 个答案:

答案 0 :(得分:3)

控制文件ACL通过标题x-goog-acl处理,在计算签名URL时也必须包含标题http://jsfiddle.net/Lvc0u55v/3991/。为了公众可读性,请使用值public-read

示例客户端代码:

let request = new XMLHttpRequest()
request.onreadystatechange = () => {
  if (request.readyState === XMLHttpRequest.DONE) {
    if (request.status === 200) {
      console.log(`Google Cloud Storage upload was successful:`, request.responseText)
    } else {
      console.log(`Google Cloud Storage upload was not successful: ${request.status}`)
    }
  }
}

request.open('PUT', signedUrl, true)
// Don't care about content-type header for signature calculation
request.setRequestHeader('content-type', 'ignore')
request.setRequestHeader('x-goog-acl', 'public-read')
request.send(file)

示例服务器端代码(用于获取签名URL):

let gcloud = require('gcloud')
let moment = require('moment')

let gcs = gcloud.storage({
  projectId: process.env.GCLOUD_PROJECT_ID,
  credentials: {
    client_email: process.env.GCLOUD_CLIENT_EMAIL,
    private_key: process.env.GCLOUD_PRIVATE_KEY,
  },
})

let bucket = gcs.bucket('aBucket')
let cloudFile = bucket.file('aFile')
cloudFile.getSignedUrl({
  action: 'write',
  expires: moment.utc().add(1, 'days').format(),
  contentType: 'ignore',
  extensionHeaders: {'x-goog-acl': 'public-read',},
}, (error, signedUrl) => {
  if (error != null) {
    console.log(`Failed to obtain signed URL for file`)
  } else {
    console.log(`Got signed URL for file: ${signedUrl}`)
  }
})