Eu consigo resgatar o nome do arquivo assim,
$this->params['form']['meu_campo']
Só que desta forma aparentemente não tenho aceso ao handler para poder
manipular o arquivo, somente o nome do arquivo está disponível.
Alguém tem solução?
Falopa!
function startup(&$controller){
$this->path = APP.WEBROOT_DIR.DS;
$this->maxSize = 2*1024*1024; // 2MB
}
function setPath($p){
if ($p!=NULL){
$this->path = $this->path.$p;
$this->path = eregi_replace("/", DS, $this->path);
$this->path = eregi_replace("\\\\", DS, $this->path);
return true;
}
}
function setMaxFileSize($size){
$this->maxSize = $size;
}
function addAllowedExt($ext){
if (is_array($ext)){
$this->allowedExtensions = array_merge($this-
>allowedExtensions, $ext);
}else{
array_push($this->allowedExtensions, $ext);
}
}
function getExt($file){
$p = explode(".", $file);
return $p[count($p)-1];
}
function copyUploadedFile($source, $destination){
$pass = false;
if (is_uploaded_file($_FILES[$source]["tmp_name"])){
if ($_FILES[$source]["size"] < $this->maxSize){
if (count($this->allowedExtensions)==0){
// dont make validation
$pass = true;
}else{
// make validation
$pass = false;
foreach($this->allowedExtensions as $ext){
if (eregi(".*".$ext."$",$_FILES[$source]["name"])){
$pass = true;
}
}
}
}
if ($pass){
// make upload
$ext = $this->getExt($_FILES[$source]
["name"]);
move_uploaded_file($_FILES[$source]["tmp_name"], $this->path.
$destination.".".$ext);
}else{
// dont make the upload
}
}
}
}
?>
abraços,
$this->params['form']['File']
É isso?
Falopa!
[]'s
Preto no branco:
Não consegui usar isso até agora. Já mexi de tudo quanto é jeito e
nada de upload.
Vamos lá, tutorial inverso (existe isso?)
Eu criei 3 campos do tipo file, nome-ei-os como "file0", "file1" e
"file2"...
E no controller eu coloco:
$this->Upload->copyUploadedFile( "file". $i ."", $this->params['file'.
$i ] );
ou coloco
$this->Upload->copyUploadedFile( "file". $i, "file". $i );
Tentei das duas formas e nada...
Explica ai direitinho.
Falopa!
Primeiro:
- colocar o var $components = array("Upload");
Segundo:
- no view crie um campo file normal, por exemplo:
<input type="file" name="arquivo1">
Terceiro:
- na hora de receber esse arquivo no controller:
$this->Upload->setPath("imagens"); // considerando esta pasta dentro
de webroot que recebera o arquivo
$this->Upload->copyUploadedFile("arquivo1",
"nomedoarquivonoservidorSemExtensao"); // vai retornar true se o
arquivo foi copiado com sucesso! olhar a extensao se ela está na lista
de permitidas, vide $allowedExtensions no component.
Prontex!
Espero ter ajudado..
Abraços...
Dei uma mudadinha no seu componente para usar... Peço sua aprovação.
Mas antes. Galera... Não use o cake (HTML helper) para criar o campo de
formulário nesse caso. Use o bom e velho HTML:
CERTO
<input type="file" id="imagem" name="imagem"/>
ERRADO (gerado pelo cake)
<input type="file" id="MaterialImagem" name="data[Material][imagem]"/>
Abraços
Voltando. Túlio, o componente modificado:
---[corte daqui para baixo, estrague seu monitor ]--8<---
<?php
class UploadComponent extends Object{
var $controller = true;
var $path = "";
var $maxSize;
var $allowedExtensions = array("jpg", "jpeg", "gif", "png");
function startup(&$controller){
$this->path = APP . WEBROOT_DIR . DS;
$this->maxSize = 2*1024*1024; // 2MB
}
function setPath($p){
if ($p!=NULL){
$this->path = $this->path . $p . DS;
$this->path = eregi_replace("/", DS, $this->path);
$this->path = eregi_replace("\\\\", DS, $this->path);
return true;
}
}
function setMaxFileSize($size){
$this->maxSize = $size;
}
function addAllowedExt($ext){
if (is_array($ext)){
$this->allowedExtensions =
array_merge($this->allowedExtensions, $ext);
}else{
array_push($this->allowedExtensions, $ext);
}
}
function getExt($file){
$p = explode(".", $file);
return $p[count($p)-1];
}
function verifyUpload($file){
$passed = false;
if(is_uploaded_file($file["tmp_name"])){
$ext = $this->getExt($file["name"]);
if((count($this->allowedExtensions) == 0) ||
(in_array($ext, $this->allowedExtensions))){
$passed = true;
}
}
return $passed;
}
function copyUploadedFile($source, $destination){
if($this->verifyUpload($_FILES[$source])){
move_uploaded_file(
$_FILES[$source]["tmp_name"],
$this->path . $destination . DS . $_FILES[$source]["name"]);
}
}
}
?>
Falopa!
Aproveitei e comentei o codigo.
Uma recomendação a mais é não esquecer do enctype="multipart/form-
data" do form.
Obs.: Talvez o code não seja o mais perfeito e otimizado. Criticas e
sugestões, estão abertas.
<?php
/**
* Upload class file.
*
* @Autor Tulio Faria
* @Contribuição Helio Ricardo, Vinicius Cruz
* @Link http://www.tuliofaria.net
* @Licença MIT
* @Versão x.x $Data: xx-xx-2007
*/
class UploadComponent extends Object{
var $controller = true;
var $path = "";
var $maxSize; //Tamanho máximo permitido
var $allowedExtensions = array("jpg", "jpeg", "gif", "png"); //
Arquivos permitidos
var $logErro = ""; //Log de erro
function startup(&$controller){
$this->path = APP . WEBROOT_DIR . DS;
$this->maxSize = 2*1024*1024; // 2MB
}
function setPath($p)
{
if ($p!=NULL){
$this->path = $this->path . $p . DS;
$this->path = eregi_replace("/", DS, $this->path);
$this->path = eregi_replace("\\\\", DS, $this->path);
return true;
}
}
//Seta novo tamanho máximo
function setMaxFileSize($size)
{
$this->maxSize = $size;
}
//Adiciona nova extensão no array
function addAllowedExt($ext)
{
if (is_array($ext))
{
$this->allowedExtensions = array_merge($this-
>allowedExtensions, $ext);
}else{
array_push($this->allowedExtensions, $ext);
}
}
//Retorna extensão de arquivo
function getExt($file)
{
$p = explode(".", $file);
return $p[count($p)-1];
}
//Exibe lista de extensões em array
function viewExt()
{
$list_tmp = "";
for($a=0; $a<count($this->allowedExtensions); $a++)
{
$list_tmp.= $this->allowedExtensions[$a].", ";
}
return substr($list_tmp, 0, -2);
}
//Verifica se arquivo pode ser feito upload
function verifyUpload($file)
{
$passed = false; //Variável de controle
if(is_uploaded_file($file["tmp_name"]))
{
$ext = $this->getExt($file["name"]);
if((count($this->allowedExtensions) == 0) ||
(in_array($ext, $this->allowedExtensions)))
{
$passed = true;
}
}
return $passed;
}
//Copia arquivo para destino
function copyUploadedFile($source, $destination="")
{
//Destino completo
$this->path = $this->path . $destination . DS;
//Cabeçalho de log de erro
$logMsg = '=============== UPLOAD LOG ===============<br />';
$logMsg .= 'Pasta destino: ' . $this->path . '<br />';
$logMsg .= 'Nome do arquivo: ' . $_FILES[$source]["name"] . '<br /
>';
$logMsg .= 'Tamanho do arquivo: ' . $_FILES[$source]["size"] . '
bytes<br />';
$logMsg .= 'Tipo de arquivo: ' . $_FILES[$source]["type"] . '<br /
>';
$logMsg .=
'---------------------------------------------------------------<br /
>';
$this->setLog($logMsg);
//Verifica se arquivo é permitido
if($this->verifyUpload($_FILES[$source]))
{
if(move_uploaded_file($_FILES[$source]["tmp_name"], $this-
>path . $this->verifyFileExists($_FILES[$source]["name"])))
return true;
else
{
$this->setLog("-> Erro ao enviar arquivo<br />");
$this->setLog(" Obs.: ".$this-
>getErrorUpload($_FILES[$source]["error"])."<br />");
return false;
}
}else
{
$this->setLog("-> O arquivo que você está tentando enviar
não é permitido pelo administrador<br />");
$this->setLog(" Obs.: Apenas as extensões ".$this-
>viewExt()." são permitidas.<br />");
return false;
}
}
//Gerencia log de erro
function setLog($msg)
{
$this->logErro.=$msg;
}
function getLog()
{
return $this->logErro;
}
function getErrorUpload($cod="")
{
switch($cod)
{
case 1:
return "Arquivo com tamanho maior que definido no servidor.";
break;
case 2:
return "Arquivo com tamanho maior que definido no formulário de
envio.";
break;
case 3:
return "Arquivo enviado parcialmente.";
break;
case 4:
return "Não foi possível realizar upload do arquivo.";
break;
case 5:
return "The servers temporary folder is missing.";
break;
case 6:
return "Failed to write to the temporary folder.";
break;
}
}
//Checa se arquivo já existe no servidor, e renomea
function verifyFileExists($file)
{
if(!file_exists($this->path.$file))
return $file;
else
return $this->renameFile($file);
}
//Renomea Arquivo, para evitar sobescrever
function renameFile($file)
{
$ext = $this->getExt($file); //Retorna extensão do arquivo
$file_tmp = substr($file, 0, -4); //Nome do arquivo, sem
extensao
do
{
$file_tmp.= base64_encode(date("His"));
echo $file_tmp."<br>";
}while(file_exists($this->path.$file_tmp.".".$ext));
return $file_tmp.".".$ext;
}
}
?>
Parabéns pela excelente colaboração Helio e Vinicius
On 6 set, 12:17, Vinicius Cruz <vinaoc...@gmail.com> wrote:
> Bom, acabei também alterando algumas coisas do componente do Tulio, em
> cima do que Helio tinha alterado. Se me permite, Tulio.. =D
> As alterações são a seguinte:
> - Registro de log
> - Evita sobescrever, caso já exista um arquivo com mesmo nome. Nesse
> caso, ele renomeia arquivo
>
> Aproveitei e comentei o codigo.
> Uma recomendação a mais é não esquecer do enctype="multipart/form-
> data" do form.
>
> Obs.: Talvez o code não seja o mais perfeito e otimizado. Criticas e
> sugestões, estão abertas.
>
> <?php
> /**
> * Upload class file.
> *
> * @Autor Tulio Faria
> * @Contribuição Helio Ricardo, Vinicius Cruz
> * @Linkhttp://www.tuliofaria.net