本文介绍了重命名非农产品市场准入的上传ZF2 + AWS S3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何重命名前上传ZF2和Amazon S3的文件的名称?这是我的code:

  $文件= $请求 - >的GetFiles();
$ bucketname ='mybucket';
$结果= $ aws-> putObject(阵列(
'斗'=> $ bucketname,
'关键'=> 用户/ 5 /'.$文件['图像文件'] ['名称'],
身体=> EntityBody ::工厂(FOPEN($文件['图像文件'] ['tmp_name的值'],'R')),
ACL=> CannedAcl :: PUBLIC_READ,
'的ContentType'=> 为image / jpeg
));
 

我不能使用该模块 https://github.com/aws/aws- SDK-PHP-ZF2

解决方案

 命名空间管理\表;

使用Zend的\表\表;
类SubcategoryimageForm扩展表
{
    公共职能__construct($名= NULL)
    {
        父:: __结构(Subcategoryimage');
        $这个 - >的setAttribute('法','后');
        $这个 - >的setAttribute(加密类型,多部分/表单数据);


        $这个 - >添加(阵列(
                '名'=> 'ID',
                '属性'=>阵列(
                        '类型'=> '隐',

                ),
        ));
        $这个 - >添加(阵列(
                '名'=> subcategory_link_id,
                '属性'=>阵列(
                        '类型'=> '隐',
                ),
        ));
        $这个 - >添加(阵列(
            '名'=> ALT,
            '属性'=>阵列(
                '类型'=> '文本',
            ),
            '选项'=>阵列(
                标签=> 替换文本,
            ),
        ));


        $这个 - >添加(阵列(
            '名'=> '上传文件',
            '属性'=>阵列(
                '类型'=> '文件',
            ),
            '选项'=>阵列(
                标签=> '上传文件',
            ),
        ));

        $这个 - >添加(阵列(
                '名'=> '详情',
                '属性'=>阵列(
                        '类型'=> 文本域
                ),
                '选项'=>阵列(
                        标签=> '详情'
                )
        ));
        $这个 - >添加(阵列(
                '类型'=> Zend的\表\元素\复选框',
                '名'=> '活性',
                '的tabindex'=> 3,
                '选项'=>阵列(
                        标签=> '活性',
                        use_hidden_​​element'=>真正,
                        checked_value'=> '1',
                        unchecked_value'=> '0'
                )
        ));
        $这个 - >添加(阵列(
                '类型'=> Zend的\表\元素\无线电通讯,
                '名'=> '位置',
                '选项'=>阵列(
                        标签=> 请选择选项之一,
                        value_options'=>阵列(
                                '1'=> '旗',
                                '2'=> '降落',
                                '3'=> 主页,
                        ),
                ),
                '属性'=>阵列(
                        '值'=> '1'//组检查,以'1'
                )
        ));
        $这个 - >添加(阵列(
                '名'=> '提交',
                '类型'=> '提交',
                '的tabindex'=> 5,
                '大小'=> 20,
                '需要'=>假,
                '属性'=>阵列(
                        '值'=> '上传文件',
                        'ID'=> 提交按钮
                )
        ));
    }
}
 

在你的控制器

// inculde的想象模块

 使用的Zend \ Validatior \文件\大小;
用想象\钆\想象;
用想象\图片\盒;
用想象\图片\点;
公共职能imageAction()
    {

        $ ID =(INT)$这个 - > PARAMS() - > fromRoute('身份证',0);
        如果(!$ ID){
            返回$这个 - >重定向() - > toRoute('类');
        }

        $形式=新SubcategoryimageForm();
        $形式 - >获得(subcategory_link_id') - >的setAttribute('值',$ id)的;
        $请求= $这个 - >调用getRequest();
        如果($请求 - > isPost()){
            //使某些合并文件的信息!
            $形象=新Subcategoryimage();
            $形式 - > setInputFilter($图像 - > getInputFilter());
            $后= array_merge_recursive(
                    $请求 - >的getPost() - >的toArray()
                    $请求 - >的GetFiles() - >的toArray()
            );

            $形式 - >使用setData($后);

            如果($形式 - >的isValid()){

                $大小=新\ Zend的\验证\文件\ IMAGESIZE(阵列(
                        '了minWidth'=> 30,了minHeight'=> 30,
                        '了maxWidth'=> 1024'了maxHeight'=> 920,
                )); //最低字节文件大小
                $ isImage =新\ Zend的\验证\文件\ IsImage();
                $ MIMETYPE =新\ Zend的\验证\文件\ Mime类型(阵列(图像/ GIF,图像/ JPG,图像/ JPEG,图像/ PNG','enableHeaderCheck'=>真));
                $适配器=新\ Zend的\文件\传输\适配器\ HTTP();
                $适配器 - > setValidators(数组($大小),$后期['文件上传'] ['名称']);
                $适配器 - > setValidators(数组($ isImage),$后期['文件上传'] ['名称']);
                $适配器 - > setValidators(数组($ MIMETYPE),$后期['文件上传'] ['名称']);

                如果($适配器 - >!的isValid()){
                    $ dataError = $适配器 - >的getMessages();
                    $错误=阵列();
                    的foreach($ dataError为$关键=> $行)
                    {
                        $错误[] = $行;
                    }
                    $形式 - > setMessages(阵列('文件上传'=> $错误));
                    $消息= $形式 - >的getMessages();

                    返回$这个 - >重定向() - > toRoute('类');
                    //的print_r($消息);死(文件错误);

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

                    $适配器 - > setDestination('imagepathtosave');

                    如果($适配器 - >接收($后期['文件上传'] ['名称'])){

                        $图像 - > exchangeArray($形式 - >的getData());

                        开关(用strtolower($ _ FILES ['文件上传'] ['型']))
                        {
                            案为image / jpeg':
                                $文件名= imagecreatefromjpeg('的ImagePath /'.$后['文件上传'] ['名称']);
                                打破;
                            案图像/ PNG:
                                $文件名= imagecreatefrompng('的ImagePath /'.$后['文件上传'] ['名称']);
                                打破;
                            案图像/ GIF:
                                $文件名= imagecreatefromgif('的ImagePath /'.$后['文件上传'] ['名称']);
                                打破;
                            默认:
                                退出(不支持的类型:。$ _ FILES ['文件上传'] ['型']);
                        }

                        ob_start()函数;
                        imagejpeg($文件名);
                        //大图
                        $大= base64_en code(ob_get_contents()); //返回输出

                        $ mainimgWidth = imagesx($文件名);
                        $ mainimgHeight = imagesy($文件名);

                        $ thumbWidth = INTVAL($ mainimgWidth / 4);
                        $ thumbHeight = INTVAL($ mainimgHeight / 4);
                        $新= imagecreatetruecolor($ thumbWidth,$ thumbHeight);
                        $的backgroundColor = imagecolorallocate($新的,255,255,255);
                        imagefill($新,0,0,$的backgroundColor);
                        imagecopyresampled($新,$文件名,0,0,0,0,$ thumbWidth,$ thumbHeight,$ mainimgWidth,$ mainimgHeight);

                        / **抓住的ImageData * /
                        ob_start()函数;

                        imagejpeg($新);

                        $数据= ob_get_clean();

                        //破坏资源
                        imagedestroy($文件名);
                        imagedestroy($新);

                        //设置新的内容,类型和状态code
                        $拇指= base64_en code($的数据);
                        //想象库在测试服务器通过amarjit intsalled由作曲家

                        ob_end_clean();

                        $想象=新的想象();
                        //重命名文件
                        $ Filedata上=阵列(
                                'ID'=> $岗位['身份证'],
                                subcategory_link_id'=> $岗位['subcategory_link_id'],
                                ALT => $岗位['ALT'],
                                '细节'=> $岗位['细节'],
                                活跃=> $岗位['主动'],
                                位置=> $岗位['位置'],
                                '大拇指'=> $大拇指,
                                大=> $大,
                                '创建'=>日期(Y-M-D H:我:S'),
                                createdby'=> 1,
                        );

                        的$ id = $这个 - > getImageTable() - >节省($ Filedata上);
                        $ imagine->开('ipathofimage /'.$发布['文件上传'] ['名称'])
                         - >保存(pathtosaveimages / newnameofimage  - '的$ id。JPG。);
                        / **
                         *删除原始上传文件的;
                        * /
                        取消链接(映像路径/'.$发布['文件上传'] ['名称']);
                        返回$这个 - >重定向() - > toRoute('类');

                    }
                }
            }其他{
                $消息= $形式 - >的getMessages();

            }
        }

        返回数组(

                'ID'=> $ ID,
                '形式'=> $形式,
                '实体'=> $这个 - > getImageTable() - > getImageContents($ ID),
        );
    }
 

从数据库中获取的图像

低于code使用在动作

 公共职能getlandingimageAction()
    {

        $ ID =(INT)$这个 - > PARAMS() - > fromRoute('身份证',0);
        如果(!$ ID){
            返回$这个 - >重定向() - > toRoute('类');
        }

        尝试 {

            $拇指= $这个 - > getImageTable() - >的getImage($ ID);
        }赶上(\ $例外前){
            返回$这个 - >重定向() - > toRoute(类,阵列(
                    '行动'=> '指数'
            ));
        }

        $图像= base64_de code($大拇指);

        / **检查图像数据库* /
        如果($形象!= NULL)
        {

            $ db_img = imagecreatefromstring($图像);
            标题(内容类型:image / JPEG);
            imagejpeg($ db_img);

        }
        其他
        {

            / **检查图像上传DIR * /

            $ URL =路径/ imagename的$ id。JPG。;
            如果(file_exists($ URL))
            {
                $ db_img = imagecreatefromjpeg($网址);
                标题(内容类型:image / JPEG);
                imagejpeg($ db_img);
                出口;
            }

            / **处理,如果图像不退出* /
            / **
             *此需要从吨改变
             * /
            $ imgUrl的=paaathofimage /;
            标题(内容类型:image / GIF);
            $ I = imagecreatefromgif($ imgUrl的/图片/ noimg.gif。);
            imagegif($ I);

        }

        出口;
    }
 

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

解决方案
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;
    }

这篇关于重命名非农产品市场准入的上传ZF2 + AWS S3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 15:29