簡體   English   中英

從本地主機或外部服務器上傳文件到 Google Cloud Storage

[英]Uploading files to Google Cloud Storage from Localhost or external server

我想通過我的本地主機或外部服務器中托管的 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)

和平的向導比反對票更受贊賞。

為了從 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

您可以創建一個上傳 URL。 這樣,用戶就可以使用 HTML 表單將文件上傳到 GCS,請查看此文檔 它具有使用 PHP 執行此操作所需的所有信息。

我寫了一個包下載/獲取本地文件並上傳到谷歌雲存儲,也許對你有幫助: 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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM