如何使用预签名的 URL 而不是凭证直接从浏览器上传到 AWS S3? [英] How to upload to AWS S3 directly from browser using a pre-signed URL instead of credentials?

查看:24
本文介绍了如何使用预签名的 URL 而不是凭证直接从浏览器上传到 AWS S3?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们想使用 Javascript AWS SDK 将文件上传到 S3,但根本不使用凭证.使用凭证上传有效,但我们无法为每个应用程序用户生成一个 AWS IAM 用户(或者我们应该?)

We'd like to use Javascript AWS SDK to upload files to S3, but without using credentials at all. Uploading using credentials works, but we cannot generate an AWS IAM user for each of our app users (or should we?)

因此,与使用 GET 类似,我们希望服务器生成一个预签名的 URL,将其发送到浏览器,然后让浏览器上传到该 URL.

Therefore, similar to using GET, we'd like the server to generate a pre-signed URL, send it to browser, and have the browser upload to that URL.

但是,没有关于如何完成此操作的示例.此外,如果没有设置凭据,即使在上传到 S3 请求之前,SDK 也会出现

However, there are no examples on how to accomplish this. Also, if not setting a credential, even before making the upload to S3 request, the SDK errors with

code: "CredentialsError"
message: "No credentials to load"

JS SDK 文档提到了这一点,所以似乎有可能:

The JS SDK docs mention this, so it seems it would be possible:

Pre-signing a putObject (asynchronously)
var params = {Bucket: 'bucket', Key: 'key'};
    s3.getSignedUrl('putObject', params, function (err, url) {
      console.log('The URL is', url);
});

推荐答案

让老问题保持沉默,但它确实帮助我最终完成了它.我的解决方案是基于 PHP 和 JavaScript 和 jQuery.

Quiet the old question but it did help me a bit to get it finally done. My solution is based on PHP and JavaScript with jQuery.

我在 https://github.com/JoernBerkefeld/s3SignedUpload 中很好地包装了整个解决方案,但是以下是要点:

I have the entire solution nicely wrapped at https://github.com/JoernBerkefeld/s3SignedUpload but here are the essentials:

api.php:

<?php
require_once '/server/path/to/aws-autoloader.php';
use AwsCommonAws;

$BUCKET = "my-bucket";
$CONFIG = "path-to-iam-credentials-file-relative-to-root.php"

function getSignedUrl($filename, $mime) {
    $S3 = Aws::factory( $CONFIG )->get('S3');
    if(!$filename) {
        return $this->error('filename missing');
    }
    if(!$mime) {
        return $this->error('mime-type missing');
    }
    $final_filename = $this->get_file_name($filename);
    try {
        $signedUrl = $S3->getCommand('PutObject', array(
            'Bucket' => $BUCKET,
            'Key' => $this->folder . $final_filename,
            'ContentType' => $mime,
            'Body'        => '',
            'ContentMD5'  => false
        ))->createPresignedUrl('+30 minutes');
    } catch (S3Exception $e) {
        echo $e->getMessage() . "
";
    }
    $signedUrl .= '&Content-Type='.urlencode($mime);
    return $signedUrl;
}


echo getSignedUrl($_GET['filename'],$_GET['mimetype']);

请确保在您的 api.php 中添加用户身份验证.否则,知道该文件路径的每个人都可以将文件上传到您的存储桶.

please make sure to add user authentication to your api.php. Else everyone who knows the path to that file could upload files to your bucket.

credentials.inc.php:

credentials.inc.php:

<?php
return array(
    'includes' => array('_aws'),
    'services' => array(
        'default_settings' => array(
            'params' => array(
                'key'    => 'MY-ACCESS-KEY',
                'secret' => 'MY-SECRECT',
                'region'  => 'eu-west-1' // set to your region
            )
        )
    )
);

client.js:

$("input[type=file]").onchange = function () {
    for (var file, i = 0; i < this.files.length; i++) {
        file = this.files[i];
        $.ajax({
            url : s3presignedApiUri,
            data: 'file='+ file.name + '&mime=' + file.type,
            type : "GET",
            dataType : "json",
            cache : false,
        })
        .done(function(s3presignedUrl) {
            $.ajax({
                url : s3presignedUrl,
                type : "PUT",
                data : file,
                dataType : "text",
                cache : false,
                contentType : file.type,
                processData : false
            })
            .done(function(){
                console.info('YEAH', s3presignedUrl.split('?')[0].substr(6));
            }
            .fail(function(){
                console.error('damn...');
            }
        })
    }
};

s3 cors设置(实际需要PUT & OPTIONS,但不能直接启用OPTIONS...):

s3 cors settings (PUT & OPTIONS are actually needed, but cannot enable OPTIONS directly...):

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <AllowedMethod>POST</AllowedMethod>
        <AllowedMethod>PUT</AllowedMethod>
        <AllowedMethod>HEAD</AllowedMethod>
        <AllowedMethod>DELETE</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>*</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

这篇关于如何使用预签名的 URL 而不是凭证直接从浏览器上传到 AWS S3?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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