Rename nama in upload ZF2 + AWS S3

六眼飞鱼酱① 提交于 2019-12-25 11:01:13

问题


How can I rename the name of a file before to upload zf2 and Amazon S3? This is my code:

$files   = $request->getFiles();
$bucketname = 'mybucket';
$result = $aws->putObject(array(
'Bucket' => $bucketname,
'Key'    => 'user/5/'.$files['image-file']['name'],
'Body'   => EntityBody::factory(fopen($files['image-file']['tmp_name'], 'r')),
'ACL'    => CannedAcl::PUBLIC_READ,
'ContentType' => 'image/jpeg'
));

I can not use the module https://github.com/aws/aws-sdk-php-zf2


回答1:


This is a working example t upload the image in zf2,rename it and save to database

namespace Admin\Form;

use Zend\Form\Form;
class SubcategoryimageForm extends Form
{
    public function __construct($name = null)
    {
        parent::__construct('Subcategoryimage');
        $this->setAttribute('method', 'post');
        $this->setAttribute('enctype','multipart/form-data');


        $this->add(array(
                'name' => 'id',
                'attributes' => array(
                        'type'  => 'hidden',

                ),
        ));
        $this->add(array(
                'name' => 'subcategory_link_id',
                'attributes' => array(
                        'type'  => 'hidden',
                ),
        ));
        $this->add(array(
            'name' => 'alt',
            'attributes' => array(
                'type'  => 'text',
            ),
            'options' => array(
                'label' => 'Alt Text',
            ),
        ));


        $this->add(array(
            'name' => 'fileupload',
            'attributes' => array(
                'type'  => 'file',
            ),
            'options' => array(
                'label' => 'File Upload',
            ),
        ));

        $this->add ( array (
                'name' => 'detail',
                'attributes' => array (
                        'type' => 'textarea'
                ),
                'options' => array (
                        'label' => 'Detail'
                )
        ) );
        $this->add ( array (
                'type' => 'Zend\Form\Element\Checkbox',
                'name' => 'active',
                'tabindex' => 3,
                'options' => array (
                        'label' => 'Active',
                        'use_hidden_element' => true,
                        'checked_value' => '1',
                        'unchecked_value' => '0'
                )
        ) );
        $this->add(array(
                'type' => 'Zend\Form\Element\Radio',
                'name' => 'location',
                'options' => array(
                        'label' => 'Please choose one of the choices',
                        'value_options' => array(
                                '1' => 'flag',
                                '2' => 'landing',
                                '3' => 'home page',
                        ),
                ),
                'attributes' => array(
                        'value' => '1' //set checked to '1'
                )
        ));
        $this->add ( array (
                'name' => 'submit',
                'type' => 'Submit',
                'tabindex' => 5,
                'size' => 20,
                'required' => false,
                'attributes' => array (
                        'value' => 'Upload File',
                        'id' => 'submitbutton'
                )
        ) );
    }
}

In your controller

//inculde the imagine modules

use Zend\Validatior\File\Size;
use Imagine\Gd\Imagine;
use Imagine\Image\Box;
use Imagine\Image\Point;
public function imageAction()
    {

        $id = ( int ) $this->params ()->fromRoute ( 'id', 0 );
        if (! $id) {
            return $this->redirect ()->toRoute ( 'category' );
        }

        $form = new SubcategoryimageForm();
        $form->get ( 'subcategory_link_id' )->setAttribute ( 'value', $id );
        $request = $this->getRequest();
        if ($request->isPost()) {
            // Make certain to merge the files info!
            $image = new Subcategoryimage();
            $form->setInputFilter($image->getInputFilter());
            $post = array_merge_recursive(
                    $request->getPost()->toArray(),
                    $request->getFiles()->toArray()
            );

            $form->setData($post);

            if ($form->isValid()) {

                $size = new \Zend\Validator\File\ImageSize(array(
                        'minWidth' => 30, 'minHeight' => 30,
                        'maxWidth' => 1024, 'maxHeight' => 920,
                )); //minimum bytes filesize
                $isImage = new \Zend\Validator\File\IsImage();
                $mimeType = new \Zend\Validator\File\MimeType(array('image/gif', 'image/jpg','image/jpeg','image/png','enableHeaderCheck' => true));
                $adapter = new \Zend\File\Transfer\Adapter\Http();
                $adapter->setValidators(array($size), $post['fileupload']['name']);
                $adapter->setValidators(array($isImage), $post['fileupload']['name']);
                $adapter->setValidators(array($mimeType), $post['fileupload']['name']);

                if (!$adapter->isValid()){
                    $dataError = $adapter->getMessages();
                    $error = array();
                    foreach($dataError as $key=>$row)
                    {
                        $error[] = $row;
                    }
                    $form->setMessages(array('fileupload'=>$error ));
                    $messages = $form->getMessages();

                    return $this->redirect ()->toRoute ( 'category' );
                    // print_r($messages);die('file errors');

                } else {
                    //$adapter->setDestination(dirname(__DIR__).'imageurltosaveimage/');

                    $adapter->setDestination('imagepathtosave');

                    if ($adapter->receive($post['fileupload']['name'])) {

                        $image->exchangeArray($form->getData());

                        switch(strtolower($_FILES['fileupload']['type']))
                        {
                            case 'image/jpeg':
                                $filename = imagecreatefromjpeg('imagepath/'.$post['fileupload']['name']);
                                break;
                            case 'image/png':
                                $filename = imagecreatefrompng('imagepath/'.$post['fileupload']['name']);
                                break;
                            case 'image/gif':
                                $filename = imagecreatefromgif('imagepath/'.$post['fileupload']['name']);
                                break;
                            default:
                                exit('Unsupported type: '.$_FILES['fileupload']['type']);
                        }

                        ob_start();
                        imagejpeg($filename);
                        // large image
                        $large = base64_encode(ob_get_contents()); // returns output

                        $mainimgWidth  = imagesx($filename);
                        $mainimgHeight = imagesy($filename);

                        $thumbWidth = intval($mainimgWidth / 4);
                        $thumbHeight = intval($mainimgHeight / 4);
                        $new = imagecreatetruecolor($thumbWidth, $thumbHeight);
                        $backgroundColor = imagecolorallocate($new, 255, 255, 255);
                        imagefill($new, 0, 0, $backgroundColor);
                        imagecopyresampled($new, $filename, 0, 0, 0, 0, $thumbWidth, $thumbHeight, $mainimgWidth, $mainimgHeight);

                        /** Catch the imagedata */
                        ob_start();

                        imagejpeg($new);

                        $data = ob_get_clean();

                        // Destroy resources
                        imagedestroy($filename);
                        imagedestroy($new);

                        // Set new content-type and status code
                        $thumb = base64_encode($data);
                        // imagine library was intsalled by the composer in the test server by amarjit

                        ob_end_clean();

                        $imagine = new Imagine();
                        //rename files
                        $filedata = array(
                                'id'        => $post ['id'],
                                'subcategory_link_id'   => $post ['subcategory_link_id'],
                                'alt'       => $post ['alt'],
                                'detail'    => $post ['detail'],
                                'active'    => $post ['active'],
                                'location'    => $post ['location'],
                                'thumb'     => $thumb,
                                'large'     => $large,
                                'created'   => date('Y-m-d H:i:s'),
                                'createdby'   => 1,
                        );

                        $id =  $this->getImageTable ()->save ( $filedata );
                        $imagine->open('ipathofimage/'.$post['fileupload']['name'])
                        ->save('pathtosaveimages/newnameofimage-'.$id.'.jpg');
                        /**
                         * delete the origional uploaded file;
                        */
                        unlink('pathtoimage/'.$post['fileupload']['name']);
                        return $this->redirect ()->toRoute ( 'category' );

                    }
                }
            }else{
                $messages = $form->getMessages();

            }
        }

        return array (

                'id' => $id,
                'form' => $form,
                'entities' => $this->getImageTable ()->getImageContents($id),
        );
    }

To get the image from database

use below code in your action

public function getlandingimageAction()
    {

        $id = ( int ) $this->params ()->fromRoute ( 'id', 0 );
        if (! $id) {
            return $this->redirect ()->toRoute ( 'category' );
        }

        try {

            $thumb = $this->getImageTable ()->getImage ( $id );
        } catch ( \Exception $ex ) {
            return $this->redirect ()->toRoute ( 'category', array (
                    'action' => 'index'
            ) );
        }

        $image = base64_decode($thumb);

        /** check if the image is db */
        if($image!=null)
        {

            $db_img = imagecreatefromstring($image);
            Header("Content-type: image/jpeg");
            imagejpeg($db_img);

        }
        else
        {

            /** check if the image is upload dir */

            $url= "path/imagename".$id.'.jpg';
            if(file_exists($url))
            {
                $db_img = imagecreatefromjpeg($url);
                Header("Content-type: image/jpeg");
                imagejpeg($db_img);
                exit;
            }

            /** handle  if the image does not exit */
            /**
             * This needs to be changed from t
             */
            $imgurl= "paaathofimage/";
            Header("Content-type: image/gif");
            $i=imagecreatefromgif($imgurl."/images/noimg.gif");
            imagegif($i);

        }

        exit;
    }


来源:https://stackoverflow.com/questions/17613440/rename-nama-in-upload-zf2-aws-s3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!