2

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: The temp file is not formatted in any format, it's an unformatted file.

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!

Abdul Rehman
  • 5,326
  • 9
  • 77
  • 150

2 Answers2

4

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

Dat Tran
  • 1,576
  • 1
  • 12
  • 16
  • Hi @Dat_Tran, can I get the file url after uploading to google cloud storage bucket? – Abdul Rehman Aug 03 '18 at 17:32
  • I have updated the answer adding information about URL. Please accept my answer if you find it resolve your problem in the question. – Dat Tran Aug 04 '18 at 00:34
0

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

Khadreal
  • 671
  • 9
  • 15