【问题标题】:PHP, ajax, HTML form to upload file to google cloud storagePHP、ajax、HTML 表单上传文件到谷歌云存储
【发布时间】:2020-04-02 00:51:26
【问题描述】:

我看到很多问题都在问同样的问题,但我无法弄清楚这里的问题是什么。我正在尝试通过 PHP、ajax 和 HTML 将文件上传到 Google Cloud Storage:

PHP 文件

<?php
require_once 'vendor/autoload.php';
use Google\Cloud\Storage\StorageClient;

if(isset($_FILES['file'])){
    $errors= array();
    // Authentication with Google Cloud Platform
    $client = new StorageClient(['keyFilePath' => 'qpack-325-13-9bc27ee4320d.json']);
    $bucket = $client->bucket('qpack-13-img');

    // Upload a file to the bucket.
    $bucket->upload(
    fopen($_FILES['file']['tmp_name'], 'r')
    );
}

?>

JQuery/Ajax:

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script>
    $(document).on('submit', '#imageUpload', function (e) {
    e.preventDefault();
    var data = new FormData($('#imageUpload').get(0));
    $.ajax({
        type: 'POST',
        url: 'config.php',
        data: data,
        processData: false,
        contentType: false,
        success: function ($data) {
            console.log('Succcess');
            $('#success').attr('hidden', false);
        }
    });
  });
  </script>

还有 HTML:

<form id="imageUpload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <button type="submit">Use this photo</button>
</form>

但它不会工作!它不会引发任何错误,ajax 调用会记录“成功”,但没有任何内容上传到存储桶。我给了 allUsers 存储对象查看器权限,我正在部署中对其进行测试,但仍然没有。我是否错过了什么,因为我似乎无法弄清楚。

我认为它可能与 app.yaml 有关,所以我将其包含在此处:

runtime: php
env: flex

runtime_config:
  document_root: .

# [START gae_flex_storage_yaml]
env_variables:
  GOOGLE_STORAGE_BUCKET: "***"
# [END gae_flex_storage_yaml]

【问题讨论】:

    标签: php ajax google-app-engine cloud-storage


    【解决方案1】:

    您提到您已授予Storage Object Viewer 权限,但这些权限不足以在您的存储上创建文件,如果您检查Object Permissions documentation,您可以检查您应该使用storage.objects.create 创建文件,此外,根据应用的需要考虑授予storage.objects.updatestorage.objects.delete 权限可能会很有趣。

    注意:可能在后台发生错误并以某种方式被捕获或处理,但无论如何都会向您的 AJAX 调用抛出成功状态。

    【讨论】:

    • 我已经尝试过了,但仍然没有。我编辑了问题以包含 yaml 文件,因为也许这就是问题所在。我已经尝试在我的计算机(Windows)上将密钥设置为环境变量,但这没有用。有没有我遗漏的步骤?
    • 存储桶中是否已有文件?尝试手动添加一个以检查一切是否正常,然后尝试再次运行您的应用。
    猜你喜欢
    • 1970-01-01
    • 2016-12-30
    • 1970-01-01
    • 1970-01-01
    • 2015-02-28
    • 1970-01-01
    • 2018-10-10
    • 2019-06-09
    • 1970-01-01
    相关资源
    最近更新 更多