使用php和Amazon S3 sdk上传及下载文件

使用php和Amazon S3 sdk上传及下载文件,下载Excel文件时总是报文件损坏的错误,解决方案如下

上传

require 'vendor/autoload.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

$bucket = '*** Your Bucket Name ***';
$keyname = '*** Your Object Key ***';
                        
$s3 = new S3Client([
    'version' => 'latest',
    'region'  => 'us-east-1'
]);

try {
    // Upload data.
    $result = $s3->putObject([
        'Bucket' => $bucket,
        'Key'    => $keyname,
        'SourceFile' => $filePath//絶対経路
    ]);

    // Print the URL to the object.
    echo $result['ObjectURL'] . PHP_EOL;
} catch (S3Exception $e) {
    echo $e->getMessage() . PHP_EOL;
}

下载

require 'vendor/autoload.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

$bucket = '*** Your Bucket Name ***';
$keyname = '*** Your Object Key ***';

$s3 = new S3Client([
    'version' => 'latest',
    'region'  => 'us-east-1'
]);

try {
    // Get the object.
    $result = $s3->getObject([
        'Bucket' => $bucket,
        'Key'    => $keyname
    ]);

    // Display the object in the browser.
    header("Content-Type: {$result['ContentType']}");
    //echo $result['Body'];
} catch (S3Exception $e) {
    echo $e->getMessage() . PHP_EOL;
} finally {
    ob_end_clean();//aws文件下载后,excel打不开,csv文件多了一行,是在文件读写后没有关闭流,所以出现文件损坏错误时可以加上这个试试
    echo isset($result["Body"]) ? $result['Body'] : '';
}	

你可能感兴趣的:(使用php和Amazon S3 sdk上传及下载文件)