简体   繁体   English

如何使用Codeigniter / PHP将文件上传到amazon S3?

[英]How can I upload a file to amazon S3 with Codeigniter/PHP?

I'm trying to upload a file to my Amazon S3 bucket. 我正在尝试将文件上传到我的Amazon S3存储桶。 My friend had this working on our site in the past but a year later its busted and I can't figure out what's wrong. 我的朋友过去曾在我们的网站上工作,但一年后它被破坏了,我无法弄清楚出了什么问题。 We are using the S3 PHP library developed by Geoff gaudreault . 我们正在使用Geoff gaudreault开发的S3 PHP库

This library looks pretty straightforward to me, really it looks like there is one key function: putObject() . 这个库看起来非常简单,看起来有一个关键函数: putObject()

Unfortunately, I'm not even getting out of the gate. 不幸的是,我甚至没有走出大门。 I'm getting the following error message: Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data. 我收到以下错误消息: Error 324 (net::ERR_EMPTY_RESPONSE): The server closed the connection without sending any data.

Here's my codeigniter PHP for my upload form action : 这是我的上传表单action codeigniter PHP:

    function s3(){

    $config['upload_path'] = $_SERVER["DOCUMENT_ROOT"].'/temp/';
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size'] = '1000000';
    $config['max_width']  = '1024000';
    $config['max_height']  = '768000';

    $this->load->library('upload', $config);

    if ( ! $this->upload->do_upload())
    {
        $error = array('error' => $this->upload->display_errors());

        print_r($error);
        echo 'failure';
    }
    else
    {
       $data = array('upload_data' => $this->upload->data()); 
        $fn = $data['file_name'];
        $type = substr($fn, strrpos($fn, '.') + 1);

    $this->load->library('s3');
    $temp_file_path = $_SERVER["DOCUMENT_ROOT"]."/temp/" . $data['file_name'];
    $contents = read_file($temp_file_path); // will this blow up or timeout for large files?! 
    $newFileName = uniqid().".".substr($temp_file_path, strrpos($temp_file_path, '.') + 1);
     $contentPath = "mysite.com/Images"; 

    $this->s3->putObject($newFileName, $contents, $contentPath, 'private', $type);
    echo 'success';
    }
}

Does anyone have any thoughts? 有人有想法吗?

I switched to a different S3 PHP library , which is also referred to as S3.php, that is part of this really nice Netuts tutorial source code. 我切换到另一个S3 PHP库 ,也称为S3.php,这是这个非常好的Netuts教程源代码的一部分。

Just plugging in my AWS keys and bucket name into the demo's page.php file, I was able to upload to my bucket in like 2 minutes. 只需将我的AWS密钥和存储桶名称插入到demo的page.php文件中,我就可以在2分钟内上传到我的存储桶。 So this tutorial is super easy. 所以本教程非常简单。 Very exciting! 很刺激!

in codeigniter 在codeigniter

Here link to upload and delete image in s3 bucket 这里链接到s3存储桶中的上传删除图像

<?php

function profile_upload()
{
    //print_r($_FILES);
    if ($this->session->userdata('user_login')) {

        $file = $_FILES['agent_profile_file']['tmp_name'];

        if (file_exists($file)) {
            $allowedExts = array("gif", "jpeg", "jpg", "png");
            $typefile    = explode(".", $_FILES["agent_profile_file"]["name"]);
            $extension   = end($typefile);

            if (!in_array(strtolower($extension), $allowedExts)) {
                //not image
                $data['message'] = "images";
            } else {
                $userid = $this->session->userdata['user_login']['userid'];

                $full_path = "agent_image/" . $userid . "/profileImg/";

                /*if(!is_dir($full_path)){
                mkdir($full_path, 0777, true);
                }*/
                $path = $_FILES['agent_profile_file']['tmp_name'];

                $image_name = $full_path . preg_replace("/[^a-z0-9\._]+/", "-", strtolower(uniqid() . $_FILES['agent_profile_file']['name']));
                //move_uploaded_file($path,$image_name);

                $data['message'] = "sucess";

                $s3_bucket = s3_bucket_upload($path, $image_name);

                if ($s3_bucket['message'] == "sucess") {
                    $data['imagename'] = $s3_bucket['imagepath'];
                    $data['imagepath'] = $s3_bucket['imagename'];
                }

                //print_r($imagesizedata);
                //image
                //use $imagesizedata to get extra info
            }
        } else {
            //not file
            $data['message'] = "images";
        }

    } else {
        $data['message'] = "login";
    }
    echo json_encode($data);
    //$file_name2 = preg_replace("/ /", "-", $file_name);
}

// Helper file add code
// image compress code
function compress($source, $destination, $quality)
{
    ob_start();
    $info = getimagesize($source);

    if ($info['mime'] == 'image/jpeg') {
        $image = imagecreatefromjpeg($source);
    } elseif ($info['mime'] == 'image/gif') {
        $image = imagecreatefromgif($source);
    } elseif ($info['mime'] == 'image/png') {
        $image = imagecreatefrompng($source);
    }

    $filename = tempnam(sys_get_temp_dir(), "beyondbroker");

    imagejpeg($image, $filename, $quality);

    //ob_get_contents();
    $imagedata = ob_end_clean();
    return $filename;
}

// type for if image then it will reduce size
// site for it in web of mobile because mobile webservice image will in base 64
// $tempth will file temp path
// $image_path will file where to save path

function s3_bucket_upload($temppath, $image_path, $type = "image", $site = "web")
{
    $bucket = "bucket-name";

    $data = array();

    $data['message'] = "false";

    // For website only
    if ($site == "web") {
        if ($type == "image") {
            $file_Path = compress($temppath, $image_path, 90);
        } else {
            $file_Path = $temppath;
        }
    }

    try {
        $s3Client = new S3Client([
            'version'     => 'latest',
            'region'      => 'us-west-2',
            'credentials' => [
                'key'    => 'aws-key',
                'secret' => 'aws-secretkey',
            ],
        ]);

        // For website only
        if ($site == "web") {

            $result = $s3Client->putObject([
                'Bucket'     => $bucket,
                'Key'        => $image_path,
                'SourceFile' => $file_Path,
                //'body'=> $file_Path,
                'ACL'        => 'public-read',
                //'StorageClass' => 'REDUCED_REDUNDANCY',
            ]);

            $data['message']   = "sucess";
            $data['imagename'] = $image_path;
            $data['imagepath'] = $result['ObjectURL'];
        } else {
            // $tmp = base64_decode($base64);
            $upload            = $s3Client->upload($bucket, $image_path, $temppath, 'public-read');
            $data['message']   = "sucess";
            $data['imagepath'] = $upload->get('ObjectURL');
        }

    } catch (Exception $e) {
        $data['message'] = "false";
        // echo $e->getMessage() . "\n";
    }

    return $data;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM