0

如何在上传 zf2 和 Amazon S3 之前重命名文件名?这是我的代码:

$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'
));

我无法使用模块https://github.com/aws/aws-sdk-php-zf2

4

1 回答 1

0

这是一个工作示例,将图像上传到 zf2,重命名并保存到数据库

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'
                )
        ) );
    }
}

在您的控制器中

//包括想象模块

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),
        );
    }

从数据库中获取图像

在您的操作中使用以下代码

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;
    }
于 2013-11-18T16:15:55.403 回答