从Localhost或外部服务器将文件上传到Google Cloud Storage [英] Uploading files to Google Cloud Storage from Localhost or external server

查看:84
本文介绍了从Localhost或外部服务器将文件上传到Google Cloud Storage的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to upload files to Google Cloud Storage (Bucket) through my PHP or JavaScript application which is hosted in my localhost or external server.

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

As I tried the Google Cloud Storage has the dedicated support to upload files from Google App Engine but that's not I want to achieve.

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

Since I went through this link which is give idea on Google JSON APIs: https://cloud.google.com/storage/docs/json_api/v1/how-tos/simple-upload

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

However this is not a helpful resource as I tried.

场景:

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

I have a localhost PHP application with HTML form of file upload button, once I submitted the form it should upload the chosen file to my Google Bucket with cURL - API or any client side scripting.

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

和平的向导比不赞成的人最多.

Peaceful guides are most appreciated than down votes.

推荐答案

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

In order to upload files to Google Cloud Storage from outside of App Engine or from your external server you have to install the client library of the programming language you use.

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

Step 1:
Create a Google Service Account Key from the below URL and download the json file which has all of your crenditial information to login from the client 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 -客户

这篇关于从Localhost或外部服务器将文件上传到Google Cloud Storage的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆