Upload and Retrieve Image from Google Cloud Storag

2019-07-31 10:39发布

问题:

I am very new to all of this. I am trying to take an uploaded image from my iPhone app and store it into my Google Cloud Storage bucket (gs://app/users/profile_pics/) using PHP. I was able to do this with the local file system but it isn't working with Google Cloud Storage.

**iOS Code (this works)**
...
[body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:profile_pic_data]];
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
...

**PHP Code to local file system (works using local file system)**
if($_POST) {
...
    //Make user directory to house files
    $upload_dir = 'user_data/' . $user_id . '/'; 
    $path = mkdir("$upload_dir", 0777);

    //Save file to newly created folder
    $file = 'profile_pic.jpg';
    $profile_pic_path = $upload_dir . $file;
    if (move_uploaded_file($_FILES['file']['tmp_name'], $profile_pic_path)) {
        //Profile pic uploaded, Update profile pic field in database
        $query = "UPDATE users SET profile_image_path='$upload_path' WHERE email='$user_email'";
        if(mysql_query($query)){
            echo json_encode(array('success' => 1,'info_message' => "")); // Account fully created!
        }
...

**PHP using Google Cloud Storage (not working, trying the most simple version first)**
...
if($_POST) {
...
    $gs_name = $_FILES['file']['tmp_name'];
    move_uploaded_file($gs_name, 'gs://socalityapp/users/profile_pics/profile_pic.jpg');
...

I can't seem to get it to store. I know the rest of my php is working because I am saving the profiles into my Google Cloud SQL database.

An help or critique (iOS, PHP, etc.) would be very appreciative!!!

回答1:

The cloud storage is not on the same machine as the appengine. You'll never be able to use the local filesystem on appengine.

When you receive the post with the form submission, you need to pass that data of the image onwards to the storage. I could not see a php example, but you can reference the JSON API to interact with the storage. You should be able to use Buzz to do a simple upload

POST https://www.googleapis.com/upload/storage/v1/b/myBucket/o?uploadType=media&name=myObject