php - 如何直接从 url 将文件上传到 S3 存储桶
问题描述
我从我的用户那里收到了一些彩信。那些彩信是通过 twilio 来的。所以 twilio 将这些文件存储到他们的服务器中,我可以从 twilio 访问这些文件。但就我而言,我需要将这些文件存储到 S3 并从 S3 显示到我们的系统中。我可以将这些文件存储到我的本地文件夹或服务器中。但我没有找到任何方法将文件直接从 url 存储到 S3 中。这是我从 url 存储到本地目录中所做的。
// url of my file. Mostly it will be image.
$url = 'urlofmyfile';
// Path where I am saving. Keeping for jpg for now
$img = 'file/sms/file.jpg';
// saving the file into the folder
file_put_contents($img, file_get_contents($url));
如果有人想将文件直接上传到我的系统中,这就是我将文件保存到 S3 的方式。例如,如果任何用户想要上传他们的个人资料图片。
public function saveToS3Bucket($uploadFileName, $imageTmpName) {
$s3Client = new \Aws\S3\S3Client([
'version' => env('S3_BUCKET_VERSION'),
'region' => env('S3_BUCKET_REGION'),
'credentials' => array(
'key' => env('S3_BUCKET_KEY'),
'secret' => env('S3_BUCKET_SECRET'),
)
]);
try {
$s3Client->putObject([
'Bucket' => env('S3_BUCKET_NAME'),
'Key' => $uploadFileName,
'SourceFile' => $imageTmpName,
'StorageClass' => 'REDUCED_REDUNDANCY',
'ACL' => 'public-read'
]);
return true;
} catch (S3Exception $e) {
echo $e->getMessage() . PHP_EOL;
return false;
}
}
以上代码工作正常。但我没有找到任何方法从 url 存储到 S3 中。请注意我正在用 CakePHP 编写代码。
解决方案
看看下面的Twilio 函数,它应该为您指明正确的方向。
它来自这个 Twilio 博客:
const axios = require('axios');
let AWS = require('aws-sdk');
const S3UploadStream = require('s3-upload-stream');
exports.handler = async function(context, event, callback) {
// Set the region
AWS.config.update({region: 'us-west-2'});
AWS.config.update({ accessKeyId: context.AWSaccessKeyId, secretAccessKey: context.AWSsecretAccessKey });
// The name of the bucket that you have created
const BUCKET_NAME = 'winston';
const fileUrl = "https://a.b.twil.io/assets/KittehWinston.jpg";
const fileName = "winston.jpg";
const s3Stream = S3UploadStream(new AWS.S3());
// call S3 to retrieve upload file to specified bucket
let upload = s3Stream.upload({Bucket: BUCKET_NAME, Key: fileName, ContentType: 'image/jpeg', ACL: 'public-read' });
const fileUpload = await uploadFile(fileUrl, upload)
.then(result => callback(null, `success: ${JSON.stringify(result)}`))
.catch(err => callback(err.message));
async function uploadFile (url, upload) {
const response = await axios({
url,
method: 'GET',
responseType: 'stream'
})
response.data.pipe(upload);
return new Promise((resolve, reject) => {
upload.on('uploaded', resolve)
upload.on('error', reject)
})
}
};
推荐阅读
- java - 通过Java每天根据预定时间自动备份MySql DB
- flutter - 如何在 Flutter 中绘制自定义背景?
- go - 为什么这个零长度和零容量切片不为零?
- javascript - React / Axios - “代码”:400,“消息”:“必需参数:部分”
- python - 读取大量图像时出现内存错误
- java - 动态 JPA 标准构建器
- python - 如何抓取 HTML 代码的不可见部分
- css - 如何修复 Chrome 和 Safari 之间的高度差?
- java - 整数可以是原始的,但 assertTrue 变得模棱两可——如何同时满足这两个要求?
- c# - System.InvalidOperationException:未知错误:Runtime.evaluate 抛出异常:DOMException error using Azure and Selenium through C#