Upload a file to Google Cloud Storage Bucket with PHP and Ajax

≡放荡痞女 提交于 2019-12-11 07:57:34

问题


I'm working on a PHP project in which I need to upload a file (provided by an HTML form) to the Google Cloud Storage Bucket. The form request will be received as an ajax request. My file is uploading successfully but inside the bucket, it shows a temp file but I have uploaded an image file.

Here's what I have tried:

PHP File:

if(isset($_FILES['file'])){
    $errors= array();
    // Authentication with Google Cloud Platform
    $client = new StorageClient(['keyFilePath' => 'api-project-374381085870-eaf930d9ffd7.json']);
    $bucket = $client->bucket('storage_client');

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

Ajax Code:

    $(document).on('submit', '#fileForm', function (e) {
    e.preventDefault();
    var data = new FormData($('#fileForm').get(0));
    $.ajax({
        type: 'POST',
        url: 'gcp_storage.php',
        data: data,
        processData: false,
        contentType: false,
        success: function ($data) {
            console.log('Succcess');
            $('#success').attr('hidden', false);
        }
    });
});

HTML Code:

<form id="fileForm" action="" method="post" enctype="multipart/form-data">
    <div class="form-row">
        <br/>
        <div class="form-group">
            <label for="textFile">Text File: </label>
            <br/>
            <input type="file" name="file" id="textFile">
        </div>
    </div>
    <br>
    <button type="submit" class="btn btn-lg btn-primary"> Upload </button>
</form>

Here's how an image file looks inside bucket:

Update:

Now, I have changed:

this:

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

to:

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

It's uploading the files successfully but the file extension doesn't display inside the bucket. So, is there a way I can rename the file before uploading to google cloud storage bucket?

Help me, please!

Thanks in advance!


回答1:


add $options params with name solve the problem.

$bucket->upload(
    fopen($_FILES['file']['tmp_name'], 'r'),
    ['name' => 'some-name.jpg']
);    

More info can be found in the source code: https://github.com/GoogleCloudPlatform/google-cloud-php/blob/master/Storage/src/Bucket.php

More information:

the result of $bucket->upload is an StorageObject. You can get the signed URL through:

$obj = $bucket->upload(...);
$url = $obj->signedUrl(new Timestamp(new DateTime('tomorrow'))); 

More info can be found in https://github.com/GoogleCloudPlatform/google-cloud-php/tree/master/Storage/src.

information of signed URLS: https://cloud.google.com/storage/docs/access-control/signed-urls




回答2:


You can use pathinfo() to get both the filename and extension.

$file = pathinfo($_FILES['file']['name']);
$prefix = uniqid('prefix_', true); //generate random string to avoid name conflicts
$filename = $prefix . "." . $file['extension'];

$bucket->upload(
  fopen($_FILES['file']['tmp_name'], 'r'),
  ['name' => $filename]
);  

This wont only save the file with extension to GCP bucket but generates random name for each file to avoid name conflicts



来源:https://stackoverflow.com/questions/51665251/upload-a-file-to-google-cloud-storage-bucket-with-php-and-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!