文件上传不适用于表单追加,但适用于s3存储桶中的表单

时间:2019-06-11 16:51:30

标签: jquery amazon-s3

我正在使用AWS s3存储桶,当我使用var form_data = new FormData(this);时它工作正常,但是当我使用这样的表单附加时,它却无法工作,

                var form_data = new FormData();
                form_data.append('key', filename);
                form_data.append('acl', 'public-read');
                form_data.append('Content-Type', the_file.type);
                form_data.append("file", the_file);
                form_data.append("success_action_status", 201);
                form_data.append("policy", $('input[name=policy]').val());
                form_data.append("X-amz-credential", $('input[name=X-amz-credential]').val());
                form_data.append("X-amz-algorithm", $('input[name=X-amz-algorithm]').val());
                form_data.append("X-amz-date", $('input[name=X-amz-date]').val());
                form_data.append("X-amz-expires", $('input[name=X-amz-expires]').val());
                form_data.append("X-amz-signature", $('input[name=X-amz-signature]').val());

我需要使用表单附加,因为我在一种表单中上传了很多文件,因此我无法在一种表单中使用多种表单,这是我的aws s3上传的完整代码,任何人都可以帮助我如何工作带有表单追加?

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>Untitled Document</title>
        <style type="text/css">
            h1{text-align:center}
            .form-wrp {width: 350px;margin: 30px auto 0px;background: #02cce6;padding: 20px;}
            #results span{padding: 20px;background: #00bfd8;margin: 5px 0;text-align: center;box-shadow: inset 0px 0px 3px 0px rgba(0, 0, 0, 0.06);border: 1px solid #00b4cc;display: block;}
        </style>
    </head>
    <body>
        <?php
        $access_key = "********"; //User Access Key
        $secret_key = "**********"; //secret key
        $my_bucket = "******"; //bucket name
        $region = "ap-south-1"; //bucket region
        $allowd_file_size = "1048579, 10485760"; 
        $short_date = gmdate('Ymd'); //short date
        $iso_date = gmdate("Ymd\THis\Z"); //iso format date
        $expiration_date = gmdate('Y-m-d\TG:i:s\Z', strtotime('+1 hours')); //policy expiration 1 hour from now
        $presigned_url_expiry = 3600; //Presigned URL validity expiration time (3600 = 1 hour)

        $policy = array(
            'expiration' => gmdate('Y-m-d\TG:i:s\Z', strtotime('+6 hours')),
            'conditions' => array(
                array('bucket' => $my_bucket),
                array('acl' => 'public-read'),
                array('starts-with', '$key', ''),
                array('starts-with', '$Content-Type', ''),
                array('success_action_status' => '201'),
                array('x-amz-credential' => implode('/', array($access_key, $short_date, $region, 's3', 'aws4_request'))),
                array('x-amz-algorithm' => 'AWS4-HMAC-SHA256'),
                array('x-amz-date' => $iso_date),
                array('x-amz-expires' => '' . $presigned_url_expiry . ''),
        ));

        $policybase64 = base64_encode(json_encode($policy));

        $kDate = hash_hmac('sha256', $short_date, 'AWS4' . $secret_key, true);
        $kRegion = hash_hmac('sha256', $region, $kDate, true);
        $kService = hash_hmac('sha256', "s3", $kRegion, true);
        $kSigning = hash_hmac('sha256', "aws4_request", $kService, true);
        $signature = hash_hmac('sha256', $policybase64, $kSigning);
        ?>
        <h1>Ajax Upload to Amazon AWS S3</h1>
        <div class="form-wrp">
            <div id="results"> server response here </div>
            <form action="https://<?= $my_bucket ?>.s3-<?= $region ?>.amazonaws.com" method="post" id="aws_upload_form"  enctype="multipart/form-data">
                <input type="hidden" name="acl" value="public-read">
                <input type="hidden" name="success_action_status" value="201">
                <input type="hidden" name="policy" value="<?= $policybase64 ?>">
                <input type="hidden" name="X-amz-credential" value="<?= $access_key ?>/<?= $short_date ?>/<?= $region ?>/s3/aws4_request">
                <input type="hidden" name="X-amz-algorithm" value="AWS4-HMAC-SHA256">
                <input type="hidden" name="X-amz-date" value="<?= $iso_date ?>">
                <input type="hidden" name="X-amz-expires" value="<?= $presigned_url_expiry ?>">
                <input type="hidden" name="X-amz-signature" value="<?= $signature ?>">
                <input type="hidden" name="key" value="">
                <input type="hidden" name="Content-Type" value="">
                <input type="file" name="file" />
                <input type="submit" value="Upload File" />
            </form>
        </div>

        <script type="text/javascript" src="//code.jquery.com/jquery-2.2.4.min.js"></script>
        <script>

            $("#aws_upload_form").submit(function (e) {
                e.preventDefault();
                the_file = this.elements['file'].files[0];
                var filename = Date.now() + '.' + the_file.name.split('.').pop();
                $(this).find("input[name=key]").val(filename);
                $(this).find("input[name=Content-Type]").val(the_file.type);


                var post_url = $(this).attr("action"); //get form action url
                var form_data = new FormData(this); //Creates new FormData object

                //alert($('input[name=policy]').val());

                var form_data = new FormData();
                form_data.append('key', filename);
                form_data.append('acl', 'public-read');
                form_data.append('Content-Type', the_file.type);
                form_data.append("file", the_file);
                form_data.append("success_action_status", 201);
                form_data.append("policy", $('input[name=policy]').val());
                form_data.append("X-amz-credential", $('input[name=X-amz-credential]').val());
                form_data.append("X-amz-algorithm", $('input[name=X-amz-algorithm]').val());
                form_data.append("X-amz-date", $('input[name=X-amz-date]').val());
                form_data.append("X-amz-expires", $('input[name=X-amz-expires]').val());
                form_data.append("X-amz-signature", $('input[name=X-amz-signature]').val());

                $.ajax({
                    url: post_url,
                    type: 'post',
                    datatype: 'xml',
                    data: form_data,
                    contentType: false,
                    processData: false,
                    //crossDomain:true,
                    xhr: function () {
                        var xhr = $.ajaxSettings.xhr();
                        if (xhr.upload) {
                            var progressbar = $("<div>", {style: "background:#607D8B;height:10px;margin:10px 0;"}).appendTo("#results"); //create progressbar
                            xhr.upload.addEventListener('progress', function (event) {
                                var percent = 0;
                                var position = event.loaded || event.position;
                                var total = event.total;
                                if (event.lengthComputable) {
                                    percent = Math.ceil(position / total * 100);
                                    progressbar.css("width", +percent + "%");
                                }
                            }, true);
                        }
                        return xhr;
                    }
                }).done(function (response) {
                    var url = $(response).find("Location").text(); //get file location
                    var the_file_name = $(response).find("Key").text(); //get uploaded file name
                    $("#results").html("<span>File has been uploaded, Here's your file <a href=" + url + ">" + the_file_name + "</a></span>"); //response
                }).error(function () {
                    console.log(arguments);
                });
            });

        </script>
    </body>
</html>   

0 个答案:

没有答案