gpt4 book ai didi

javascript - 从本地主机或外部服务器上传文件到谷歌云存储

转载 作者:行者123 更新时间:2023-11-29 23:08:22 32 4
gpt4 key购买 nike

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

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

自从我浏览了这个链接后,它给出了关于 Google JSON API 的想法:https://cloud.google.com/storage/docs/json_api/v1/how-tos/simple-upload

然而,正如我所尝试的那样,这并不是有用的资源。

场景:

我有一个带有 HTML 格式文件上传按钮的本地主机 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,您必须安装您使用的编程语言的客户端库。

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

第 2 步:


PHP:

Install 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):

Install 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

关于javascript - 从本地主机或外部服务器上传文件到谷歌云存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54342506/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com