Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

davidnmagalhaes

Upload de Arquivos no Banco de Dados

Recommended Posts

Olá prezados,
Estou com uma grande dúvida para fazer o upload de arquivos no banco de dados, eu consigo enviar os arquivos normalmente utilizando o move_uploaded_file, porém o meu problema é que no banco de dados aparece apenas um arquivo, vamos supor que o cliente envie 3 arquivos, os três arquivos aparecem na pasta ao efetuar o upload, porém no banco de dados aparece apenas um dos arquivos, segue abaixo o código da página:

<?php require_once('Connections/conteste.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
	if(isset($_FILES['file'])) {
    $name = $_FILES['file']['name'];
    $type = $_FILES['file']['type'];
    $size = $_FILES['file']['size'];
}

$message = '';

if(is_array($_FILES['file']['error'])) {
    foreach ($_FILES['file']['error'] as $code) {
        switch ($code) { 
            case UPLOAD_ERR_OK: 
                $message .= ""; 
                break;
            case UPLOAD_ERR_INI_SIZE: 
                $message .= "O upload do arquivo excedeu o tamanho máximo de upload (upload_max_filesize) do php.ini<br/>"; 
                break; 
            case UPLOAD_ERR_FORM_SIZE: 
                $message .= "O upload do arquivo excedeu o tamanho máximo de upload (MAX_FILE_SIZE) que foi especificado no formulário HTML<br/>"; 
                break; 
            case UPLOAD_ERR_PARTIAL: 
                $message .= "O upload do arquivo foi carregado parcialmente<br/>"; 
                break; 
            case UPLOAD_ERR_NO_FILE: 
                $message .= "Nenhum arquivo foi carregado<br/>"; 
                break; 
            case UPLOAD_ERR_NO_TMP_DIR: 
                $message .= "Missing a temporary folder<br/>"; 
                break; 
            case UPLOAD_ERR_CANT_WRITE: 
                $message .= "Falha ao escrever o arquivo no disco<br/>"; 
                break; 
            case UPLOAD_ERR_EXTENSION: 
                $message .= "File upload stopped by extension<br/>"; 
                break; 
            default: 
                $message .= "Erro de Upload Desconhecido<br/>"; 
                break; 
        } 
    }
} elseif(isset($_FILES['file']['error'])) {
    $code = $_FILES['file']['error'];
    switch ($code) { 
        case UPLOAD_ERR_OK: 
            $message .= ""; 
            break;
        case UPLOAD_ERR_INI_SIZE: 
            $message .= "The uploaded file exceeds the upload_max_filesize directive in php.ini<br/>"; 
            break; 
        case UPLOAD_ERR_FORM_SIZE: 
            $message .= "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form<br/>"; 
            break; 
        case UPLOAD_ERR_PARTIAL: 
            $message .= "The uploaded file was only partially uploaded<br/>"; 
            break; 
        case UPLOAD_ERR_NO_FILE: 
            $message .= "No file was uploaded<br/>"; 
            break; 
        case UPLOAD_ERR_NO_TMP_DIR: 
            $message .= "Missing a temporary folder<br/>"; 
            break; 
        case UPLOAD_ERR_CANT_WRITE: 
            $message .= "Failed to write file to disk<br/>"; 
            break; 
        case UPLOAD_ERR_EXTENSION: 
            $message .= "File upload stopped by extension<br/>"; 
            break; 
        default: 
            $message .= "Unknown upload error<br/>"; 
            break; 
    } 
} elseif(!isset($_FILES['file'])) {
    $message = "No files recieved<br/>";
}

$uploaddir = 'pedidos';

if(is_array($_FILES['file']['name'])) {
    foreach ($_FILES['file']['name'] as $k=>$filename) {
		
		for ($k = 0; $k < count($_FILES['file']['name']); $k++){
		
        $uploadfile = getcwd()."/".$uploaddir."/".$k.$filename;
        if(move_uploaded_file($_FILES['file']['tmp_name'][$k], $uploadfile)) {
            // ok
        } else {
            $message .= "Erro enquanto carregava o arquivo ".$filename."<br/>";
        }
		
		}//fecha
		
    }
} elseif(isset($_FILES['file']['name'])) {
	
	for ($k = 0; $k < count($_FILES['file']['name']); $k++){
	
    $uploadfile = getcwd()."/".$uploaddir."/".$_FILES['file']['name'][$k];
    if(move_uploaded_file($_FILES['file']['tmp_name'][$k], $uploadfile)) {
        // ok
    } else {
        $message = "Erro enquanto carregava o arquivo ".$_FILES['file']['name']."<br/>";
    }
	
	}//fecha
	
}
  $insertSQL = sprintf("INSERT INTO pedidos (id, nome, empresa, telefone, celular, email, observacoes, arquivos) VALUES (%s, %s, %s, %s, %s, %s, %s, '$uploadfile')",
                       GetSQLValueString($_POST['id'], "int"),
                       GetSQLValueString($_POST['nome'], "text"),
                       GetSQLValueString($_POST['empresa'], "text"),
                       GetSQLValueString($_POST['telefone'], "int"),
                       GetSQLValueString($_POST['celular'], "int"),
                       GetSQLValueString($_POST['email'], "text"),
                       GetSQLValueString($_POST['observacoes'], "text"));
					  

  mysql_select_db($database_conteste, $conteste);
  $Result1 = mysql_query($insertSQL, $conteste) or die(mysql_error());

  $insertGoTo = "envio-sucesso.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
	
  }
  header(sprintf("Location: %s", $insertGoTo));
   }
									
	
?>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Documento sem título</title>
		
        <link rel="shortcut icon" href="../favicon.ico"> 
        <link rel="stylesheet" type="text/css" href="css/demo.css" />
        <link rel="stylesheet" type="text/css" href="css/style1.css" />
		<link rel="stylesheet" type="text/css" media="all" href="styles.css" />
        <link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">
		<link rel="stylesheet" href="pe-icon-7-stroke/css/pe-icon-7-stroke.css">
    <link rel="stylesheet" href="css/drop_uploader.css">
        
		<script type="text/javascript" src="js/modernizr.custom.86080.js"></script>
        <script src="js/jquery-2.2.4.min.js"></script>
    <script src="js/drop_uploader.js"></script>
    
    <script>
        $(document).ready(function(){
            $('input[type=file]').drop_uploader({
                uploader_text: 'Drop files to upload, or',
                browse_text: 'Browse',
                browse_css_class: 'button button-primary',
                browse_css_selector: 'file_browse',
                uploader_icon: '<i class="pe-7s-cloud-upload"></i>',
                file_icon: '<i class="pe-7s-file"></i>',
                time_show_errors: 5,
            });
        });
    </script>
    
    </head>
    <body id="page">
        <ul class="cb-slideshow">
            <li><span>Image 01</span><div><h3></h3></div></li>
            <li><span>Image 02</span><div><h3></h3></div></li>
            <li><span>Image 03</span><div><h3></h3></div></li>
            <li><span>Image 04</span><div><h3></h3></div></li>
            <li><span>Image 05</span><div><h3></h3></div></li>
            <li><span>Image 06</span><div><h3></h3></div></li>
        </ul>
        <div class="container">
		<div id="logo"><img src="images/logo.png"/></div>
            <form action="<?php echo $editFormAction; ?>" method="POST" enctype="multipart/form-data" name="form1" id="form1">
            <h1 id="titulo-upload">Upload de Arquivos</h1>
            <div id="itens-form">
            <div class="twelve column"><input type="file" name="file[]" multiple></div>
  <p>
  
      <input type="hidden" name="id" id="id" />
    <input type="text" name="empresa" id="empresa" class="campos" placeholder="Empresa"/>
  </p>
  <p>
    <input type="text" name="nome" id="nome" class="campos" placeholder="Nome completo"/>
  </p>
  <p>
    <input type="text" name="telefone" id="telefone" class="campos" placeholder="Telefone"/>
  </p>
  <p>
    <input type="text" name="celular" id="celular" class="campos" placeholder="Celular"/>
  </p>
  <p>
    <input type="text" name="email" id="email" class="campos" placeholder="E-mail"/>
  </p>
  <p>
    <textarea name="observacoes" id="observacoes" cols="45" rows="5" placeholder="Observações"></textarea>
  </p>
  
  <p>
    <input type="submit" name="enviar" id="enviar" value="Enviar" />
  </p>
  <input type="hidden" name="MM_insert" value="form1" />
  </div>
          </form>

                <div class="clr"></div>
            </div><!--/ Codrops top bar -->
            
        </div>
		
	
</body>
</html>


Compartilhar este post


Link para o post
Compartilhar em outros sites

Olá.

 

O INSERT também deve estar dentro do foreach para que insira cada um dos arquivos.

 

Olá AndersonMamede, obrigado pela ajuda, fiz uma alteração no código, mas ainda não está cadastrando certo no banco de dados phpmyadmin, vou colocar o código alterado abaixo, mas agora o que acontece é o seguinte, ele move os arquivos certinho, da o nome para os arquivos com uma numeração, por exemplo, dois arquivos sendo um arquivo nomeado 0teste.jpg e outro arquivo sendo 1testando.png, a numeração vai na frente, portanto o problema está no banco de dados, pois cadastra apenas um dos arquivos, ele não cria dois ids diferentes para cada arquivo, ou junta os dois. Veja abaixo:

 

<?php require_once('Connections/conteste.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
	if(isset($_FILES['file'])) {
    $name = $_FILES['file']['name'];
    $type = $_FILES['file']['type'];
    $size = $_FILES['file']['size'];
}

$message = '';

if(is_array($_FILES['file']['error'])) {
    foreach ($_FILES['file']['error'] as $code) {
        switch ($code) { 
            case UPLOAD_ERR_OK: 
                $message .= ""; 
                break;
            case UPLOAD_ERR_INI_SIZE: 
                $message .= "O upload do arquivo excedeu o tamanho máximo de upload (upload_max_filesize) do php.ini<br/>"; 
                break; 
            case UPLOAD_ERR_FORM_SIZE: 
                $message .= "O upload do arquivo excedeu o tamanho máximo de upload (MAX_FILE_SIZE) que foi especificado no formulário HTML<br/>"; 
                break; 
            case UPLOAD_ERR_PARTIAL: 
                $message .= "O upload do arquivo foi carregado parcialmente<br/>"; 
                break; 
            case UPLOAD_ERR_NO_FILE: 
                $message .= "Nenhum arquivo foi carregado<br/>"; 
                break; 
            case UPLOAD_ERR_NO_TMP_DIR: 
                $message .= "Missing a temporary folder<br/>"; 
                break; 
            case UPLOAD_ERR_CANT_WRITE: 
                $message .= "Falha ao escrever o arquivo no disco<br/>"; 
                break; 
            case UPLOAD_ERR_EXTENSION: 
                $message .= "File upload stopped by extension<br/>"; 
                break; 
            default: 
                $message .= "Erro de Upload Desconhecido<br/>"; 
                break; 
        } 
    }
} elseif(isset($_FILES['file']['error'])) {
    $code = $_FILES['file']['error'];
    switch ($code) { 
        case UPLOAD_ERR_OK: 
            $message .= ""; 
            break;
        case UPLOAD_ERR_INI_SIZE: 
            $message .= "The uploaded file exceeds the upload_max_filesize directive in php.ini<br/>"; 
            break; 
        case UPLOAD_ERR_FORM_SIZE: 
            $message .= "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form<br/>"; 
            break; 
        case UPLOAD_ERR_PARTIAL: 
            $message .= "The uploaded file was only partially uploaded<br/>"; 
            break; 
        case UPLOAD_ERR_NO_FILE: 
            $message .= "No file was uploaded<br/>"; 
            break; 
        case UPLOAD_ERR_NO_TMP_DIR: 
            $message .= "Missing a temporary folder<br/>"; 
            break; 
        case UPLOAD_ERR_CANT_WRITE: 
            $message .= "Failed to write file to disk<br/>"; 
            break; 
        case UPLOAD_ERR_EXTENSION: 
            $message .= "File upload stopped by extension<br/>"; 
            break; 
        default: 
            $message .= "Unknown upload error<br/>"; 
            break; 
    } 
} elseif(!isset($_FILES['file'])) {
    $message = "No files recieved<br/>";
}

$uploaddir = 'pedidos';

if(is_array($_FILES['file']['name'])) {
    foreach ($_FILES['file']['name'] as $k=>$filename) {
		
		
		
        $uploadfile = getcwd()."/".$uploaddir."/".$k.$filename;
        if(move_uploaded_file($_FILES['file']['tmp_name'][$k], $uploadfile)) {
           $insertSQL = sprintf("INSERT INTO pedidos (id, nome, empresa, telefone, celular, email, observacoes, arquivos) VALUES (%s, %s, %s, %s, %s, %s, %s, '$uploadfile')",
                       GetSQLValueString($_POST['id'], "int"),
                       GetSQLValueString($_POST['nome'], "text"),
                       GetSQLValueString($_POST['empresa'], "text"),
                       GetSQLValueString($_POST['telefone'], "int"),
                       GetSQLValueString($_POST['celular'], "int"),
                       GetSQLValueString($_POST['email'], "text"),
                       GetSQLValueString($_POST['observacoes'], "text"));
        } else {
            $message .= "Erro enquanto carregava o arquivo ".$filename."<br/>";
        }
		
	
		
    }
} 
  
					  

  mysql_select_db($database_conteste, $conteste);
  $Result1 = mysql_query($insertSQL, $conteste) or die(mysql_error());

  $insertGoTo = "envio-sucesso.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
	
  }
  header(sprintf("Location: %s", $insertGoTo));
   }
									
	
?>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Documento sem título</title>
		
        <link rel="shortcut icon" href="../favicon.ico"> 
        <link rel="stylesheet" type="text/css" href="css/demo.css" />
        <link rel="stylesheet" type="text/css" href="css/style1.css" />
		<link rel="stylesheet" type="text/css" media="all" href="styles.css" />
        <link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">
		<link rel="stylesheet" href="pe-icon-7-stroke/css/pe-icon-7-stroke.css">
    <link rel="stylesheet" href="css/drop_uploader.css">
        
		<script type="text/javascript" src="js/modernizr.custom.86080.js"></script>
        <script src="js/jquery-2.2.4.min.js"></script>
    <script src="js/drop_uploader.js"></script>
    
    <script>
        $(document).ready(function(){
            $('input[type=file]').drop_uploader({
                uploader_text: 'Drop files to upload, or',
                browse_text: 'Browse',
                browse_css_class: 'button button-primary',
                browse_css_selector: 'file_browse',
                uploader_icon: '<i class="pe-7s-cloud-upload"></i>',
                file_icon: '<i class="pe-7s-file"></i>',
                time_show_errors: 5,
            });
        });
    </script>
    
    </head>
    <body id="page">
        <ul class="cb-slideshow">
            <li><span>Image 01</span><div><h3></h3></div></li>
            <li><span>Image 02</span><div><h3></h3></div></li>
            <li><span>Image 03</span><div><h3></h3></div></li>
            <li><span>Image 04</span><div><h3></h3></div></li>
            <li><span>Image 05</span><div><h3></h3></div></li>
            <li><span>Image 06</span><div><h3></h3></div></li>
        </ul>
        <div class="container">
		<div id="logo"><img src="images/logo.png"/></div>
            <form action="<?php echo $editFormAction; ?>" method="POST" enctype="multipart/form-data" name="form1" id="form1">
            <h1 id="titulo-upload">Upload de Arquivos</h1>
            <div id="itens-form">
            <div class="twelve column"><input type="file" name="file[]" multiple></div>
  <p>
  
      <input type="hidden" name="id" id="id" />
    <input type="text" name="empresa" id="empresa" class="campos" placeholder="Empresa"/>
  </p>
  <p>
    <input type="text" name="nome" id="nome" class="campos" placeholder="Nome completo"/>
  </p>
  <p>
    <input type="text" name="telefone" id="telefone" class="campos" placeholder="Telefone"/>
  </p>
  <p>
    <input type="text" name="celular" id="celular" class="campos" placeholder="Celular"/>
  </p>
  <p>
    <input type="text" name="email" id="email" class="campos" placeholder="E-mail"/>
  </p>
  <p>
    <textarea name="observacoes" id="observacoes" cols="45" rows="5" placeholder="Observações"></textarea>
  </p>
  
  <p>
    <input type="submit" name="enviar" id="enviar" value="Enviar" />
  </p>
  <input type="hidden" name="MM_insert" value="form1" />
  </div>
          </form>

                <div class="clr"></div>
            </div><!--/ Codrops top bar -->
            
        </div>
		
	
</body>
</html>


Compartilhar este post


Link para o post
Compartilhar em outros sites

  • Conteúdo Similar

    • Por ronaldoflopes
      Caso já exista algum tópico relacionado ao assunto peço que me desculpem mas não o encontrei.
       
      Estou com um problema grave no upload de arquivos em todos os sites que implementamos na empresa.
      Tudo funcionava as mil maravilhas até que de ontem para hoje simplesmente não consigo fazer o uploade de nenhum arquivo sequer.
      Isso ocorre em todas as implementações em domínios de diferentes clientes.
      Ao tentar fazer o upload de um arquivo ou imagem, obtenho o seguinte erro:
       
      Microsoft VBScript runtime error '800a01a8'
      Object required: '[undefined]'
      /upload.asp, line 278

      Ao verificar esta linha do arquivo encontrei o seguinte código que sempre funciona há mais de 5 anos e parou do nada:
      contentType = UploadRequest.Item("blob").Item("ContentType")

      Fui rastreando este erro e descobri que ele está relacionado a esta sub, BuildUploadRequest, que é quem trata os dados binários do arquivo e seta o objeto UploadRequest. Aparentemente ela parou de funcionar e não atribui nada no objeto por algum motivo que não consigo descobrir.

      Já verifiquei permissões de leitura, e até imprimi o total de bytes que está chegando por post.
      Em resumo, o arquivo está indo mas o asp não consegue tratar o binário para fazer o upload.
      Alguém pode me ajudar?
      Abaixo segue o código de um arquivo de upload que não funciona mais e antes funcionava perfeitamente:
      <% Sub BuildUploadRequest(RequestBin) PosBeg = 1 PosEnd = InstrB(PosBeg,RequestBin,getByteString(chr(13))) boundary = MidB(RequestBin,PosBeg,PosEnd-PosBeg) boundaryPos = InstrB(1,RequestBin,boundary) Do until (boundaryPos=InstrB(RequestBin,boundary & getByteString("--"))) Dim UploadControl Set UploadControl = CreateObject("Scripting.Dictionary") Pos = InstrB(BoundaryPos,RequestBin,getByteString("Content-Disposition")) Pos = InstrB(Pos,RequestBin,getByteString("name=")) PosBeg = Pos+6 PosEnd = InstrB(PosBeg,RequestBin,getByteString(chr(34))) Name = getString(MidB(RequestBin,PosBeg,PosEnd-PosBeg)) PosFile = InstrB(BoundaryPos,RequestBin,getByteString("filename=")) PosBound = InstrB(PosEnd,RequestBin,boundary) If PosFile<>0 AND (PosFile<PosBound) Then PosBeg = PosFile + 10 PosEnd = InstrB(PosBeg,RequestBin,getByteString(chr(34))) FileName = getString(MidB(RequestBin,PosBeg,PosEnd-PosBeg)) UploadControl.Add "FileName", FileName Pos = InstrB(PosEnd,RequestBin,getByteString("Content-Type:")) PosBeg = Pos+14 PosEnd = InstrB(PosBeg,RequestBin,getByteString(chr(13))) ContentType = getString(MidB(RequestBin,PosBeg,PosEnd-PosBeg)) UploadControl.Add "ContentType",ContentType PosBeg = PosEnd+4 PosEnd = InstrB(PosBeg,RequestBin,boundary)-2 Value = MidB(RequestBin,PosBeg,PosEnd-PosBeg) Else Pos = InstrB(Pos,RequestBin,getByteString(chr(13))) PosBeg = Pos+4 PosEnd = InstrB(PosBeg,RequestBin,boundary)-2 Value = getString(MidB(RequestBin,PosBeg,PosEnd-PosBeg)) End If UploadControl.Add "Value" , Value UploadRequest.Add name, UploadControl BoundaryPos=InstrB(BoundaryPos+LenB(boundary),RequestBin,boundary) Loop End Sub Function getByteString(StringStr) For i = 1 to Len(StringStr) char = Mid(StringStr,i,1) getByteString = getByteString & chrB(AscB(char)) Next End Function Function getString(StringBin) getString ="" For intCount = 1 to LenB(StringBin) getString = getString & chr(AscB(MidB(StringBin,intCount,1))) Next End Function %> <html> <head> <script language="JavaScript1.2"> function abre_janela(width, height, nome) { var top; var left; top = ( (screen.height/2) - (height/2) ) left = ( (screen.width/2) - (width/2) ) window.open('',nome,'width='+width+',height='+height+',scrollbars=yes,toolbar=no,location=no,status=no,menubar=yes,resizable=no,left='+left+',top='+top); } function confirm_delete(form) { if (confirm("Tem certeza que deseja excluir esta imagem?")) { document[form].submit();}} function high(which2){ theobject=which2 highlighting=setInterval("highlightit(theobject)",50) } function low(which2){ clearInterval(highlighting) which2.filters.alpha.opacity=20 } function highlightit(cur2){ if (cur2.filters.alpha.opacity<100) cur2.filters.alpha.opacity+=5 else if (window.highlighting) clearInterval(highlighting) } PositionX = 100; PositionY = 100; defaultWidth = 500; defaultHeight = 500; var AutoClose = true; // Do not edit below this line... // ================================ if (parseInt(navigator.appVersion.charAt(0))>=4){ var isNN=(navigator.appName=="Netscape")?1:0; var isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;} var optNN='scrollbars=no,width='+defaultWidth+',height='+defaultHeight+',left='+PositionX+',top='+PositionY; var optIE='scrollbars=no,width=150,height=100,left='+PositionX+',top='+PositionY; function popImage(imageURL,imageTitle){ if (isNN){imgWin=window.open('about:blank','',optNN);} if (isIE){imgWin=window.open('about:blank','',optIE);} with (imgWin.document){ writeln('<html><head><title>Loading...</title><style>body{margin:0px;}</style>');writeln('<sc'+'ript>'); writeln('var isNN,isIE;');writeln('if (parseInt(navigator.appVersion.charAt(0))>=4){'); writeln('isNN=(navigator.appName=="Netscape")?1:0;');writeln('isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;}'); writeln('function reSizeToImage(){');writeln('if (isIE){');writeln('window.resizeTo(100,100);'); writeln('width=100-(document.body.clientWidth-document.imagens[0].width);'); writeln('height=100-(document.body.clientHeight-document.imagens[0].height);'); writeln('window.resizeTo(width,height);}');writeln('if (isNN){'); writeln('window.innerWidth=document.imagens["George"].width;');writeln('window.innerHeight=document.imagens["George"].height;}}'); writeln('function doTitle(){document.title="'+imageTitle+'";}');writeln('</sc'+'ript>'); if (!AutoClose) writeln('</head><body bgcolor=000000 scroll="no" onload="reSizeToImage();doTitle();self.focus()">') else writeln('</head><body bgcolor=000000 scroll="no" onload="reSizeToImage();doTitle();self.focus()" onblur="self.close()">'); writeln('<img name="George" src='+imageURL+' style="display:block"></body></html>'); close(); }} </script> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> <style type="text/css"> <!-- body,td,th { font-family: Arial; font-size: 12px; color: #333; } --> </style> </head> <body style="background-color:#f8f8f8"> <% '---------------------------------------------------------------------------- ' MATA OS ACENTOS '---------------------------------------------------------------------------- Function KillAcentos(Palavra) cacento = "àáâãäèéêëìíîïòóôõöùúûüÀÁÂÃÄÈÉÊËÌÍÎÒÓÔÕÖÙÚÛÜçÇñÑ^~ºª´`'&%" sacento = "aaaaaeeeeiiiiooooouuuuAAAAAEEEEIIIOOOOOUUUUcCnN" texto = "" 'Response.Write "----"&Len(Palavra)&"---" 'Response.Write Palavra If Palavra <> "" Then For controlador = 1 To Len(Palavra) letra = Mid(Palavra, controlador, 1) pos_acento = InStr(cacento, letra) If pos_acento > 0 Then letra = Mid(sacento, pos_acento, 1) End If texto = texto & letra Next KillAcentos = lcase(Replace(texto,Chr(32), Chr(45))) End If End Function '---------------------------------------------------------------------------- ' MATA OS ACENTOS '---------------------------------------------------------------------------- Function KillAcentos2(Palavra) cacento = "àáâãäèéêëìíîïòóôõöùúûüÀÁÂÃÄÈÉÊËÌÍÎÒÓÔÕÖÙÚÛÜçÇñÑ^~ºª´`'&%" sacento = "aaaaaeeeeiiiiooooouuuuAAAAAEEEEIIIOOOOOUUUUcCnN" texto = "" 'Response.Write "----"&Len(Palavra)&"---" 'Response.Write Palavra If Palavra <> "" Then For controlador = 1 To Len(Palavra) letra = Mid(Palavra, controlador, 1) pos_acento = InStr(cacento, letra) If pos_acento > 0 Then letra = Mid(sacento, pos_acento, 1) End If texto = texto & letra Next KillAcentos2 = texto End If End Function id = "1" pasta_servidor = "teste" website_pasta = "E:\Inetpub\vhosts\multiplicacaodigital.com.br\httpdocs\" website_url = "http://www.multiplicacaodigital.com.br" StrFolder = website_pasta& "imagens\" &pasta_servidor& "\" &id& "\" 'Response.Write StrFolder fotos_limite = 8 '# CRIA A PASTA, CASO AINDA NAO EXISTA Set objFS = Nothing Set objFolder = Nothing Set objFS = Server.CreateObject("Scripting.FileSystemObject") 'Response.Write StrFolder If Not objFS.FolderExists(StrFolder) Then objFS.CreateFolder(StrFolder) End if Set objFolder = ObjFS.GetFolder(StrFolder) For Each File in objFolder.files If lcase(Right(File, 3)) = "gif" Or lcase(Right(File, 3)) = "jpg" Or lcase(Right(File, 3)) = "png" Then 'Response.Write File.Name If Not(objFS.FileExists(StrFolder&KillAcentos(File.Name))) Then File.Name = KillAcentos(File.Name) End If End If Next Set objFS = Nothing Set objFolder = Nothing x = 0 Set objFS = Server.CreateObject("Scripting.FileSystemObject") If Not objFS.FolderExists(StrFolder) Then objFS.CreateFolder(StrFolder) End if Set objFolder = ObjFS.GetFolder(StrFolder) For Each File in objFolder.files If lcase(Right(File, 3)) = "gif" Or lcase(Right(File, 3)) = "jpg" Or lcase(Right(File, 3)) = "png" Then x = x + 1 End If Next %> <table width="0%" border="0" cellspacing="8" cellpadding="0" class="texto1" style="border-bottom: 1px solid white"> <tr> <td colspan="<%=x%>"> <% If x = 0 Then %> Nao existem fotos cadastradas. <% End If %> </td> </tr> <tr> <% If Request("remover") <> "" Then Set objFS = Server.CreateObject("Scripting.FileSystemObject") If objFS.FileExists( StrFolder & Request("imagem_remover") ) Then objFS.DeleteFile( StrFolder & Request("imagem_remover") ) Set objFS = Nothing End If End If x = 0 '# EXIBE AS FOTOS QUE FORAM ENVIADAS For Each File in objFolder.files If lcase(Right(File, 3)) = "gif" Or lcase(Right(File, 3)) = "jpg" Or lcase(Right(File, 3)) = "png" Then x = x + 1 %> <form name="form_<%=x%>" method="post" action="<%=Request.ServerVariables("SCRIPT_NAME")%>?pasta_servidor=<%=pasta_servidor%>&id=<%=id%>&remover=sim&website_pasta=<%=website_pasta%>"> <input type="hidden" name="imagem_remover" value="<%=File.Name%>"> <td valign="top" align="center"><a href="<%=website_url%>/imagens/<%=Request("pasta_servidor")%>/<%=Request("id")%>/<%=File.Name%>" onClick="abre_janela(777, 550, 'popup','yes')" target="popup"><img src="<%=website_url%>/imagens/<%=pasta_servidor%>/<%=id%>/<%=File.Name%>" border="0" width="50" height="50" style="border: 1px solid black"></a><br> <input type="button" onClick="confirm_delete('form_<%=x%>')" value="Apagar"> </td> </form> <% End If Next %> </tr> </table> <% Set objFolder = Nothing Set Folder = Nothing %> <% If Request("enviar") <> "" And Request("ignorar") = "" Then byteCount = Request.TotalBytes RequestBin = Request.BinaryRead(byteCount) Dim UploadRequest Set UploadRequest = CreateObject("Scripting.Dictionary") BuildUploadRequest RequestBin contentType = UploadRequest.Item("blob").Item("ContentType") filepathname = UploadRequest.Item("blob").Item("FileName") filename = Right(filepathname,Len(filepathname)-InstrRev(filepathname,"\")) value = UploadRequest.Items("blob").Item("Value") If Lcase(Right(filename,3)) = "jpg" Or Lcase(Right(filename,3)) = "gif" Or Lcase(Right(filename,3)) = "png" then Set objFS = Server.CreateObject("Scripting.FileSystemObject") If objFS.FileExists(strFolder & filename) Then %> <script language="javascript"> alert("Erro ao enviar imagem, o arquivo '<%=filename%>' já existe na pasta de imagens do produto") </script> <% Else If LenB(value) > 400000 then %> <script language="javascript"> alert("Erro ao enviar a imagem, o tamanho do arquivo deve ser menor que 400Kb") </script> <% Else %> <br><strong>Aguarde o envio da imagem...</strong><br> <input name="progress" id="progress" value="0% enviado" style="border:none;background-color:#FFFFFF"> <table width="100" border="0" cellspacing="0" cellpadding="0" style="border: 1px inset;background-color:#FFFFFF"> <tr> <td><input name="barra" id="barra" style="border:none; background-color: orangered; height: 10; width:1" readonly></td> <td></td> </tr> </table> <% Set ScriptObject = Server.CreateObject("Scripting.FileSystemObject") filename = Replace(filename," ","") 'Response.Write "--"&filename2&"--" Set MyFile = ScriptObject.CreateTextFile( StrFolder & filename) progress = 0 n = 3 For i = 1 to LenB(value) MyFile.Write chr(AscB(MidB(value,i,1))) progress = Fix((i * 100) / LenB(value)) If n <> progress then n = progress %> <script language="javascript">document.getElementById('progress').value = "<%=n%>% enviado"</script> <script language="javascript">document.getElementById('barra').style.width = "<%=n%>"</script> <% End if Next MyFile.Close If n=progress Then %> <form name="reload" id="reload" method="post" action=""> </form> <script language=javascript> document.getElementById('reload').action =window.location + "&ignorar=sim"; document.getElementById('reload').submit(); </script> <% End If End If Set objFS = Nothing End if Else %> <script language="javascript"> alert("Erro ao enviar a imagem, lembre-se que ela deve possuir extensao PNG, JPG ou GIF"); </script> <% End If End If %> <% Set ObjFS = Server.CreateObject("Scripting.FileSystemObject") Set objFolder = ObjFS.GetFolder(StrFolder) x = 0 For Each File in objFolder.files If lcase(Right(File, 3)) = "gif" Or lcase(Right(File, 3)) = "jpg" Or lcase(Right(File, 3)) = "png" Then x = x + 1 End If Next Set ObjFS = Nothing Set objFolder = Nothing %> <table width="100%" border="0" cellspacing="20" cellpadding="0" style="background-color:#F3F3F3" class="texto1"> <tr> <form method="post" enctype="multipart/form-data" action="<%=Request.ServerVariables("SCRIPT_NAME")%>?pasta_servidor=<%=pasta_servidor%>&id=<%=id%>&enviar=sim&website_pasta=<%=website_pasta%>"> <td class="texto_pagina" valign="top"> <%If x => 8 Then%> <strong>Permitido enviar o total de 8 fotos.</strong><br> <%Else%> <strong>Envio de nova foto:</strong><br> <input type="file" name="blob" class="texto_pagina" style="width:200px" src="img/pesquisar_imagem.gif"><br><br> <input type="submit" value="Enviar"> <%End If%> </td> </form> </tr> </table> </body> </html>
    • Por leoamrl
      Estou trabalhando no desenvolvimento de um theme wordpress do zero e estou colocando uma página de "Theme Settings" nesse theme, para alterar coisas como a logo, links de ícones, copyright etc.

      Para fazer o Painel segui esse tutorial: http://wpmidia.com.br/tutoriais/tutorial-wordpress-como-criar-abas-em-sua-theme-options-page
       
      Preciso de um código HTML para colocar no Theme Settings em que eu possa fazer o upload de uma imagem, e armazenar no wordpress para que seja usada como logo.
       
      Meu código está assim:
       
      Arquivo adminsettings.php
      <?php add_action( 'init', 'wptester_admin_init' ); add_action( 'admin_menu', 'wptester_settings_page_init' ); function wptester_admin_init() { $settings = get_option( "wptester_theme_settings" ); if ( empty( $settings ) ) { $settings = array( 'wptester_intro' => 'Some intro text for the home page', 'wptester_tag_class' => false, 'wptester_ga' => false ); add_option( "wptester_theme_settings", $settings, '', 'yes' ); } } function wptester_settings_page_init() { $theme_data = get_theme_data( TEMPLATEPATH . '/style.css' ); $settings_page = add_theme_page( $theme_data['Name']. ' Theme Settings', $theme_data['Name']. ' Theme Settings', 'edit_theme_options', 'theme-settings', 'wptester_settings_page' ); add_action( "load-{$settings_page}", 'wptester_load_settings_page' ); } function wptester_load_settings_page() { if ( $_POST["wptester-settings-submit"] == 'Y' ) { check_admin_referer( "wptester-settings-page" ); wptester_save_theme_settings(); $url_parameters = isset($_GET['tab'])? 'updated=true&tab='.$_GET['tab'] : 'updated=true'; wp_redirect(admin_url('themes.php?page=theme-settings&'.$url_parameters)); exit; } } function wptester_save_theme_settings() { global $pagenow; $settings = get_option( "wptester_theme_settings" ); if ( $pagenow == 'themes.php' && $_GET['page'] == 'theme-settings' ){ if ( isset ( $_GET['tab'] ) ) $tab = $_GET['tab']; else $tab = 'homepage'; switch ( $tab ){ case 'general' : $settings['wptester_tag_class'] = $_POST['wptester_tag_class']; break; case 'footer' : $settings['wptester_ga'] = $_POST['wptester_ga']; break; case 'homepage' : $settings['wptester_intro'] = $_POST['wptester_intro']; break; } } if( !current_user_can( 'unfiltered_html' ) ){ if ( $settings['wptester_ga'] ) $settings['wptester_ga'] = stripslashes( esc_textarea( wp_filter_post_kses( $settings['wptester_ga'] ) ) ); if ( $settings['wptester_intro'] ) $settings['wptester_intro'] = stripslashes( esc_textarea( wp_filter_post_kses( $settings['wptester_intro'] ) ) ); } $updated = update_option( "wptester_theme_settings", $settings ); } function wptester_admin_tabs( $current = 'homepage' ) { $tabs = array( 'homepage' => 'Home', 'general' => 'General', 'footer' => 'Footer' ); $links = array(); echo '<div id="icon-themes" class="icon32"><br></div>'; echo '<h2 class="nav-tab-wrapper">'; foreach( $tabs as $tab => $name ){ $class = ( $tab == $current ) ? ' nav-tab-active' : ''; echo "<a class='nav-tab$class' href='?page=theme-settings&tab=$tab'>$name</a>"; } echo '</h2>'; } function wptester_settings_page() { global $pagenow; $settings = get_option( "wptester_theme_settings" ); $theme_data = get_theme_data( TEMPLATEPATH . '/style.css' ); ?> <div class="wrap"> <h2>Theme Settings</h2> <?php if ( 'true' == esc_attr( $_GET['updated'] ) ) echo '<div class="updated" ><p>Theme Settings updated.</p></div>'; if ( isset ( $_GET['tab'] ) ) wptester_admin_tabs($_GET['tab']); else wptester_admin_tabs('homepage'); ?> <div id="poststuff"> <form method="post" action="<?php admin_url( 'themes.php?page=theme-settings' ); ?>"> <?php wp_nonce_field( "wptester-settings-page" ); if ( $pagenow == 'themes.php' && $_GET['page'] == 'theme-settings' ){ if ( isset ( $_GET['tab'] ) ) $tab = $_GET['tab']; else $tab = 'homepage'; echo '<table class="form-table">'; switch ( $tab ){ case 'general' : ?> <tr> <th><label for="wptester_tag_class">Tags with CSS classes:</label></th> <td> <input id="wptester_tag_class" name="wptester_tag_class" type="checkbox" <?php if ( $settings["wptester_tag_class"] ) echo 'checked="checked"'; ?> value="true" /> <span class="description">Output each post tag with a specific CSS class using its slug.</span> </td> </tr> <?php break; case 'footer' : ?> <tr> <th><label for="wptester_ga">Insert tracking code</label></th> <td> <textarea id="wptester_ga" name="wptester_ga" cols="60" rows="5"><?php echo esc_html( stripslashes( $settings["wptester_ga"] ) ); ?></textarea><br/> <span class="description">Enter your Google Analytics tracking code</span> </td> </tr> <?php break; case 'homepage' : ?> <tr> <th><label for="wptester_intro">Text Logo</label></th> <td> <textarea id="wptester_intro" name="wptester_intro" cols="60" rows="5" ><?php echo esc_html( stripslashes( $settings["wptester_intro"] ) ); ?></textarea><br/> <span class="description">Digite o texto que irá aparecer na área da logo:</span> </td> </tr> <?php break; } echo '</table>'; } ?> <p class="submit" style="clear: both;"> <input type="submit" name="Submit" class="button-primary" value="Update Settings" /> <input type="hidden" name="wptester-settings-submit" value="Y" /> </p> </form> </div> </div> <?php } Arquivo functions.php
      <?php /* WIDGETS */ if (function_exists('register_sidebar')) { register_sidebar(array( 'name' => 'Sidebar', 'before_widget' => '<div class="widget">', 'after_widget' => '</div>', 'before_title' => '<h3>', 'after_title' => '</h3>', )); } register_nav_menu( 'main-menu', 'Menu Principal' ); /* Load up our theme options page and related code. */ if ( is_admin() ) require_once( TEMPLATEPATH . '/adminsettings.php' ); ?> Arquivo header.php [sAÍDA DAS INFORMAÇÕES DIGITADAS NO PAINEL DE ADMIN]
      <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" xmlns:og="http://opengraphprotocol.org/schema/" xmlns:fb="http://www.facebook.com/2008/fbml"> <head> <title><?php wp_title(''); ?></title> <meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" /> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="profile" href="http://gmpg.org/xfn/11" /> <link rel="stylesheet" type="text/css" media="all" href="<?php bloginfo( 'stylesheet_url' ); ?>" /> <link href="css/bootstrap.min.css" rel="stylesheet" media="screen"> <link rel="pingback" href="<?php bloginfo( 'pingback_url' ); ?>" /> <?php if ( is_singular() && get_option( 'thread_comments' ) ) wp_enqueue_script( 'comment-reply' ); wp_head(); ?> </head> <body> <header id="header-geral"> <div class="container"> <a href="./index.php"><?php $opcoes = get_option('wptester_theme_settings'); echo $opcoes['wptester_intro']; ?></a> <nav> <?php wp_nav_menu( array( 'location'=>'main-menu', 'container'=>'div', 'container-class'=>'menu', 'menu_class'=>'ul-menu' ) ); ?> </nav> </div> </header> Agradeço a atenção e a ajuda.
×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.