Upload a file to Google Cloud Storage Bucket with

2019-08-22 12:06发布

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!

2条回答
地球回转人心会变
2楼-- · 2019-08-22 13:03

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

查看更多
贪生不怕死
3楼-- · 2019-08-22 13:11

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

查看更多
登录 后发表回答