【问题标题】:Images not being upload in cakephp图像未在 cakephp 中上传
【发布时间】:2014-12-25 08:03:28
【问题描述】:

我努力想知道但无法解决,然后我来这里寻求您的帮助。请不要介意它是否超出主题,也请忍受我糟糕的英语。 当我打开 http://localhost/cakephp/posts 时,我正在尝试在 cakephp 2.x 中上传图像,然后正确上传图像,但是当我打开 http://localhost/cakephp/posts/index 时,图像不会上传。并收到错误“未找到”。

我正在使用blueimp image uploader

我查看了它的文档,但找不到解决方案。 还有一件事,索引页面中有表单,点击上传按钮<form id="fileupload" action="posts/index" method="POST" enctype="multipart/form-data">提交 编辑

动作代码

public function index() {
         $options = array(
            'upload_dir' => 'img',        
            'accept_file_types' => '/\.(gif|jpe?g|png)$/i',                    
           );
        $upload_handler = new UploadHandler($options);
    }

查看代码

 <form id="fileupload" action="posts/index" method="POST" enctype="multipart/form-data">
        <!-- Redirect browsers with JavaScript disabled to the origin page -->
        <noscript><input type="hidden" name="redirect" value="https://blueimp.github.io/jQuery-File-Upload/"></noscript>
        <!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->
        <div class="row fileupload-buttonbar">
            <div class="col-lg-7">
                <!-- The fileinput-button span is used to style the file input field as button -->
                <span class="btn btn-success fileinput-button">
                    <i class="glyphicon glyphicon-plus"></i>
                    <span>Add files...</span>
                    <input type="file" name="files[]" multiple>
                </span>
                <button type="submit" class="btn btn-primary start">
                    <i class="glyphicon glyphicon-upload"></i>
                    <span>Start upload</span>
                </button>
                <button type="reset" class="btn btn-warning cancel">
                    <i class="glyphicon glyphicon-ban-circle"></i>
                    <span>Cancel upload</span>
                </button>
                <button type="button" class="btn btn-danger delete">
                    <i class="glyphicon glyphicon-trash"></i>
                    <span>Delete</span>
                </button>
                <input type="checkbox" class="toggle">
                <!-- The global file processing state -->
                <span class="fileupload-process"></span>
            </div>
            <!-- The global progress state -->
            <div class="col-lg-5 fileupload-progress fade">
                <!-- The global progress bar -->
                <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
                    <div class="progress-bar progress-bar-success" style="width:0%;"></div>
                </div>
                <!-- The extended global progress state -->
                <div class="progress-extended">&nbsp;</div>
            </div>
        </div>
        <!-- The table listing the files available for upload/download -->
        <table role="presentation" class="table table-striped"><tbody class="files"></tbody></table>
    </form>

【问题讨论】:

  • 你应该发布你的代码,至少控制器,查看代码。
  • 这一行在控制器之前开始 App::import('Vendor', 'UploadHandler', array('file' => 'file.upload/UploadHandler.php'));这是行动 public function index() { $options = array( 'accept_file_types' => '/\.(gif|jpe?g|png)$/i', ); $upload_handler = new UploadHandler($options); }
  • 我没有答案,但我认为这个解决方案简单实用:bakery.cakephp.org/articles/tutec/2010/01/05/…
  • 请看现在,现在可能会给出代码指南来帮助我。

标签: cakephp file-upload image-uploading


【解决方案1】:

您可以通过此上传行为轻松使用 Blueimp 上传器

https://github.com/josegonzalez/cakephp-upload

例子:

add.ctp

  <?php echo $this->Form->create('Post',array('id'=>'fileupload','type'=>'file'));?>
  <div class="box-body">
        <!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->
            <div class="row fileupload-buttonbar">
                <div class="col-lg-12">
                <!-- The fileinput-button span is used to style the file input field as button -->
                    <span class="btn btn-sm btn-success fileinput-button">
                        <i class="glyphicon glyphicon-plus"></i>
                        <span>Add images...</span>
                        <?php
                            echo $this -> Form -> input('Image.name', array('type' => 'file', 'multiple' => 'multiple', 'div' => false, 'label' => false));
                        ?> 
                    </span>
                    <button type="submit" class="btn btn-sm btn-primary start">
                        <i class="glyphicon glyphicon-upload"></i>
                        <span>Start upload</span>
                    </button>
                    <button type="reset" class="btn btn-sm btn-warning cancel">
                        <i class="glyphicon glyphicon-ban-circle"></i>
                        <span>Stop</span>
                    </button>
                    <button type="button" class="btn btn-sm btn-danger delete">
                        <i class="glyphicon glyphicon-trash"></i>
                        <span>Delete</span>
                    </button>
                    <input type="checkbox" class="toggle">
                    <!-- The global file processing state -->
                    <span class="fileupload-process"></span>

                </div>
                <!-- The global progress state -->
                <div class="col-lg-12 fileupload-progress fade">
                <!-- The global progress bar -->
                    <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
                        <div class="progress-bar progress-bar-success" style="width:0%;"></div>
                    </div>
                    <!-- The extended global progress state -->
                    <div class="progress-extended">&nbsp;</div>
                </div>
            </div>
            <!-- The table listing the files available for upload/download -->
            <table  role="presentation" class="table table-striped">
                <tbody id="sortable" class="files ui-sortable">

                </tbody>
            </table>
        </div>
       .....

在 add.ctp 的末尾

<?php 
$upload_url = Router::url(array('controller'=>'posts','action'=>'upload'),true);
echo $this->Html->scriptBlock("
$(document).ready(function(){'use strict';
   $('#fileupload').fileupload({
        url : '".$upload_url."',
        maxFileSize : 1000000,
        limitConcurrentUploads: 1,
        acceptFileTypes : /(\.|\/)(gif|jpe?g|png)$/i,
        previewMaxWidth: 158,
        previewMaxHeight: 104,
        previewCrop: true

    }); 
$('#fileupload').on('fileuploadsubmit', function (e, data) {
    var inputs = data.context.find(':input');
    data.formData = inputs.serializeArray();
    });

$('#fileupload').on('fileuploadcompleted fileuploaddestroyed', function (e, data) {
    $('tbody .position').each(function( index ) {
        $(this).val(index+1);
        $('.ui-sortable').sortable();
        });
    });
$('.ui-sortable').on('sortupdate',function( event ){
        $('tbody .position').each(function( index ) {
        $(this).val(index+1);
        });
});
$('.ui-sortable').sortable({
    start: function(e, ui ){
        ui.placeholder.height(ui.helper.outerHeight());
    },
    placeholder: 'sort-highlight',
    handle: '.handle',
    forcePlaceholderSize: true,
    zIndex: 999999
}).disableSelection();

})",array('inline'=>false));
?>

PostsController.php

/**
 * admin add method
 *
 * @return void
 */

public function admin_add() {
    if ($this -> request -> is('post')) {
        $this -> request -> data = Hash::remove($this -> request -> data, 'Image.name');

        $this -> Product -> create();
        if ($this -> Post -> saveAll($this -> request -> data)) {
            $this -> Session -> setFlash(__('The post has been saved'),'flash_success');
            $this -> redirect(array('action' => 'index'));
        } else {
            $this -> Session -> setFlash(__('The post could not be saved. Please, try again.'),'flash_warning');
        }
    }
}

/**
 * upload method
 *
 * @return void
 */
public function admin_upload() {
    if ($this -> request -> is('post')) {
        $this -> layout = 'ajax';
        $this -> autoRender = false;
        $picturename = strtolower($this -> request -> data['Image']['name']['name']);
        $exploded = explode('.',$picturename);
        $file_ext = array_pop($exploded);
        $file_name = implode('_', $exploded);
        $file_name = Inflector::slug($file_name, $replacement = '_');
        $picturename = $file_name.'.'.$file_ext;
        $this -> request -> data['Image']['name']['name'] = $picturename;
        $this -> Post -> Image -> create();
        if ($this -> Post -> Image -> save($this -> request -> data)) {
            $lastID = $this -> Post -> Image -> getLastInsertID();
            $caption = $this -> request -> data['Image']['caption'];
            $name = $this -> request -> data['Image']['name']['name'];
            $url = Router::url('/', true) . 'img/posts/' . $lastID . '/lg_viw_fll_' . $name;
            $thumbnailUrl = Router::url('/', true) . 'img/posts/' . $lastID . '/lg_viw_thb_' . $name;
            $data = array(
                'files'=>array(
                    array(
                    'id' => $lastID,
                    'caption' => $caption,
                    'name' => $name,
                    'size' => $this -> request -> data['Image']['name']['size'],
                    'url' => $url,
                    'thumbnailUrl' => $thumbnailUrl,
                    'deleteUrl' => Router::url(array('admin' => true, 'controller' => 'products', 'action' => 'delete_picture', $lastID), false),
                    'deleteType' => 'POST')));


            $this -> set(compact('data'));
            $this -> set('_serialize', array('data'));

            echo json_encode($data);

        } else {
            return false;
        }
    } else {
        $this -> layout = 'ajax';
        $this -> autoRender = false;
        return false;
    }

}


public function admin_delete_picture($id = null) {
    $this -> layout = 'ajax';
    $this -> autoRender = false;
    if (!$this -> request -> is('post')) {
        throw new MethodNotAllowedException();
    }
    $this -> Post -> Image -> id = $id;
    if (!$this -> Post -> Image -> exists()) {
        throw new NotFoundException(__('Invalid post'));
    }
    if ($this -> Post -> Image -> delete()) {
        App::uses('Folder', 'Utility');
        $folder = new Folder(WWW_ROOT.'img'.DS.'posts'.DS.$id);
        $folder->delete();
        return true;
    }

}

Image.php 模型

// Post hasMany Images


public $actsAs = array(
    'Upload.Upload' => array(
        'name' => array(
            'fields' => array(
                'dir' => 'photo_dir'
                ),
            //'pathMethod' => 'primaryKey',
            'path' => '{ROOT}webroot{DS}img{DS}posts{DS}',
            //'filePermission' => 0755,
            //'create_directory' => true,
            //'removeOriginal' => false,
            //'allowed_mime' => array('image/jpeg', 'image/pjpeg', 'image/png'),
            //'allowed_ext' => array('.jpg', '.jpeg', '.png'),
            //'zoomCrop' => true,
            'thumbnailMethod' => 'php',
            'thumbnailSizes' => array(
                    'lg_idx_thb' => '262x194',
                    'lg_viw_fst' => '554x416',
                    'lg_viw_thb' => '158x104',
                    'lg_viw_fll' => '1100l',

        )
    )
);

我在很多项目中都使用了这段代码,希望对你有所帮助

【讨论】:

  • 亲爱的,我应该使用github.com/josegonzalez/cakephp-upload 插件和你的代码来上传图片?是吗 ?或者我仍然需要 blueimp
  • 使用 blueimp 作为前端上传器,使用 cakephp-upload 插件作为后端上传处理程序
猜你喜欢
  • 2014-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-31
  • 2020-02-17
  • 2019-03-24
相关资源
最近更新 更多