从Localhost或外部服务器将文件上传到Google Cloud Storage

时间:2019-01-24 08:44:30

标签: javascript php google-cloud-storage

我想通过本地主机或外部服务器中托管的PHP或JavaScript应用程序将文件上传到Google Cloud Storage(存储桶)。

我尝试使用Google Cloud Storage专门支持从Google App Engine上传文件,但这不是我想要的。

自从我经过此链接以来,该链接就Google JSON API提出了建议:https://cloud.google.com/storage/docs/json_api/v1/how-tos/simple-upload

但是,这并不是我尝试的有用资源。

场景:

我有一个带有HTML格式的文件上传按钮的localhost PHP应用程序,提交表单后,它将使用cURL-API或任何客户端脚本将所选文件上传到我的Google Bucket。

// Like below I want to send to Google Bucket
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)

与否决票相比,与众不同的人对和平向导的评价最高。

3 个答案:

答案 0 :(得分:1)

要从App Engine外部或外部服务器将文件上传到Google Cloud Storage,您必须安装使用的编程语言的客户端库。

第1步:
从下面的URL创建一个Google服务帐户密钥,然后下载json文件,其中包含您的所有凭据信息,以便从客户端PC登录。
https://console.cloud.google.com/apis/credentials

步骤2:


PHP:

  

安装composer require google/cloud-storage

<?php

# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';

use Google\Cloud\Storage\StorageClient;
use google\appengine\api\cloud_storage\CloudStorageTools;

# Your Google Cloud Platform project ID
$projectId = 'your_project_id';

# Instantiates a client
$storage = new StorageClient([
    'projectId' => $projectId,
    'keyFilePath' => 'service_account_key_json_file.json'
]);

# The name for the bucket
$bucket = $storage->bucket('bucket_name');

foreach ($bucket->objects() as $object) {
    echo "https://storage.googleapis.com/".$bucket->name()."/".$object->name().'<br>';
}

if(isset($_POST['submit'])) {

    $file = file_get_contents($_FILES['file']['tmp_name']);
    $objectName = $_FILES["file"]["name"];

    $object = $bucket->upload($file, [
        'name' => $objectName
    ]);

    echo "https://storage.googleapis.com/".$bucket->name()."/".$objectname;
}
?>


JavaScript(NodeJs):

  

安装npm install --save @google-cloud/storage

'use strict';

const express = require('express');
const formidable = require('formidable');
const fs = require('fs');
const path = require('path');

const { Storage } = require('@google-cloud/storage');
const Multer = require('multer');

const CLOUD_BUCKET = process.env.GCLOUD_STORAGE_BUCKET || 'bucket_name';
const PROJECT_ID = process.env.GCLOUD_STORAGE_BUCKET || 'project_id';
const KEY_FILE = process.env.GCLOUD_KEY_FILE || 'service_account_key_file.json';
const PORT = process.env.PORT || 8080;

const storage = new Storage({
  projectId: PROJECT_ID,
  keyFilename: KEY_FILE
});

const bucket = storage.bucket(CLOUD_BUCKET);

const multer = Multer({
  storage: Multer.MemoryStorage,
  limits: {
    fileSize: 2 * 1024 * 1024 // no larger than 5mb
  }
});

const app = express();

app.use('/blog', express.static('blog/dist'));

app.get('/', async (req, res) => {

  console.log(process.env);

  const [files] = await bucket.getFiles();

  res.writeHead(200, { 'Content-Type': 'text/html' });

  files.forEach(file => {
    res.write(`<div>* ${file.name}</div>`);
    console.log(file.name);
  });

  return res.end();

});

app.get("/gupload", (req, res) => {
  res.sendFile(path.join(`${__dirname}/index.html`));
});

// Process the file upload and upload to Google Cloud Storage.
app.post("/pupload", multer.single("file"), (req, res, next) => {

  if (!req.file) {
    res.status(400).send("No file uploaded.");
    return;
  }

  // Create a new blob in the bucket and upload the file data.
  const blob = bucket.file(req.file.originalname);

  // Make sure to set the contentType metadata for the browser to be able
  // to render the image instead of downloading the file (default behavior)
  const blobStream = blob.createWriteStream({
    metadata: {
      contentType: req.file.mimetype
    }
  });

  blobStream.on("error", err => {
    next(err);
    return;
  });

  blobStream.on("finish", () => {
    // The public URL can be used to directly access the file via HTTP.
    const publicUrl = `https://storage.googleapis.com/${bucket.name}/${blob.name}`;

    // Make the image public to the web (since we'll be displaying it in browser)
    blob.makePublic().then(() => {
      res.status(200).send(`Success!\n Image uploaded to ${publicUrl}`);
    });
  });

  blobStream.end(req.file.buffer);

});

// Start the server
app.listen(PORT, () => {
  console.log(`App listening on port ${PORT}`);
  console.log('Press Ctrl+C to quit.');
});

请参考示例https://github.com/aslamanver/google-cloud-nodejs-client

答案 1 :(得分:0)

您可以创建一个上传URL。这样,用户可以使用HTML表单将文件上传到GCS,然后选中this documentation。它具有使用PHP进行操作的所有信息。

答案 2 :(得分:0)

我写了一个软件包来下载/获取本地文件并上传到Google Cloud Storage,也许它可以帮助您: https://github.com/jeansouzak/duf

use JeanSouzaK\Duf\Duff;
use JeanSouzaK\Duf\Prepare\WebResource;
use JeanSouzaK\Duf\Prepare\LocalResource;

$duf = Duff::getInstance(Duff::GOOGLE_CLOUD_STORAGE, [
    'project_id' => 'storage-test-227305',
    'key_path' => '/home/env/storage-test-227305-8472347a39489.json'
]);

// - Chaining example -
$uploadResults = $duf->prepare([
    new LocalResource('imagem', '/home/test/images/test.jpg'),
    new WebResource('teste.png', 'https://dummyimage.com/600x400/000/fff')
])->download()->addBucket('your-bucket-name')->upload();