Ir para conteúdo

POWERED BY:

Arquivado

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

JsJuniorbr

HTTP: Problema com upload de multiplos arquivos

Recommended Posts

Olá,

Estou precisando fazer um upload de vários arquivos para o servidor via Delphi, formulario html e PHP, mas só chega 1 arquivo lá, antes vem um Access Violation, mas ainda chega 1. Siceramente não sei ao certo se o problema está no código Delphi ou no php que peguei como referência.

Segue abaixo o meu código Delphi que estou utilizando e um php que peguei como referência =>

 

procedure Http_arquivos;
 
var
 
i: integer;
arquivos: array [0..6] of String;
HTTP: TIdHTTP;
POSTData: TIdMultipartFormDataStream;
 
begin
 
arquivos[0]:= 'c:\arquivo0.bmp';
arquivos[1]:= 'c:\arquivo1.html';
arquivos[2]:= 'c:\arquivo2.html';
arquivos[3]:= 'c:\aarquiv3.jpg';
arquivos[4]:= 'c:\arquivo4.wav';
arquivos[5]:= 'c:\arquivo5.bmp';
arquivos[6]:= 'c:\arquivo6.txt';
 
  HTTP := TIdHTTP.Create(nil);
  POSTData := TIdMultipartFormDataStream.Create;
 
  for i:= 0 to Length(arquivos) do
    begin
 
      if fileexists (arquivos[i]) then  begin
      //showmessage(arquivo[i]);
 
       try
    POSTData.AddFile('userfile[]', arquivos[i], 'multipart/form-data');
 
    HTTP.Post('http://localhost/ENVIO/up.php', POSTData);
 
     finally
    POSTData.Free;
 
    end;
end;
end;
end;
 
procedure TForm1.Button1Click(Sender: TObject);
begin
Http_arquivos;
end;
 
end.

$updir = 'upload';      // Directory for uploads
$max_size = 500;            // Sets maxim size allowed for the uploaded files, in kilobytes
 
// sets an array with the file types allowed
$allowtype = array('bmp', 'gif', 'htm', 'html', 'jpg', 'jpeg', 'mp3', 'pdf', 'png', 'rar', 'zip', 'txt', 'wav');
 
// if the folder for upload (defined in $updir) doesn't exist, tries to create it (with CHMOD 0777)
if (!is_dir($updir)) mkdir($updir, 0777);
 
/** Loading the files on server **/
 
$result = array();          // Array to store the results and errors
 
// if receive a valid file from server
if (isset ($_FILES['userfile'])) {
  // checks the files received for upload
  for($f=0; $f<count($_FILES['userfile']['name']); $f++) {
    $fup = $_FILES['userfile']['name'][$f];       // gets the name of the file
 
    // checks to not be an empty field (the name of the file to have more then 1 character)
    if(strlen($fup)>1) {
      // checks if the file has the extension type allowed
      $type = end(explode('.', strtolower($fup)));
      if (in_array($type, $allowtype)) {
        // checks if the file has the size allowed
        if ($_FILES['userfile']['size'][$f]<=$max_size*1000) {
          // If there are no errors in the copying process
          if ($_FILES['userfile']['error'][$f]==0) {
            // Sets the path and the name for the file to be uploaded
            $thefile = $updir . '/' . $fup;
            // If the file cannot be uploaded, it returns error message
            if (!move_uploaded_file ($_FILES['userfile']['tmp_name'][$f], $thefile)) {
              $result[$f] = ' The file could not be copied, try again';
            }
            else {
              // store the name of the uploaded file
              $result[$f] = '<b>'.$fup.'</b> - OK';
            }
          }
        }
        else { $result[$f] = 'The file <b>'. $fup. '</b> exceeds the maximum allowed size of <i>'. $max_size. 'KB</i>'; }
      }
      else { $result[$f] = 'File type extension <b>.'. $type. '</b> is not allowed'; }
    }
  }
 
   // Return the result
  $result2 = implode('<br /> ', $result);
  echo '<h4>Files uploaded:</h4> '.$result2;
}

 

 

o html de referência usado pra montar o form html no Delphi =>

 

<form id="uploadform" action="uploader.php" method="post"
enctype="multipart/form-data" target="uploadframe" onsubmit="uploading(this); return false">
  <input type="file" class="file_up" name="userfile[]" />
  <input type="submit" value="UPLOAD" id="sub" />
</form>

Agradeço demais por todas as sugestões que enviarem :yes:

Compartilhar este post


Link para o post
Compartilhar em outros sites

Seu problema provavelmente é a forma como está usando este trecho do código:

 

 

 try 
    POSTData.AddFile('userfile[]', arquivos[i], 'multipart/form-data'); 
    HTTP.Post('http://localhost/ENVIO/up.php', POSTData); 
 finally 
    POSTData.Free; 
 end;

 

Veja que você está liberando o objeto PostData da memória ao dar o free dentro do seu looping.... e como você não o recria, ao pegar o 2° arquivo para enviar com o objeto dá o erro de Access Violation, pois você está tentando referenciar uma posição de memória que não é mais válida. Tente alterar seu código para o seguinte:

 

 

procedure Http_arquivos;
var i: integer;
    arquivos: array [0..6] of String;
    HTTP: TIdHTTP;
    POSTData: TIdMultipartFormDataStream;
begin
  arquivos[0]:= 'c:\arquivo0.bmp';
  arquivos[1]:= 'c:\arquivo1.html';
  arquivos[2]:= 'c:\arquivo2.html';
  arquivos[3]:= 'c:\aarquiv3.jpg';
  arquivos[4]:= 'c:\arquivo4.wav';
  arquivos[5]:= 'c:\arquivo5.bmp';
  arquivos[6]:= 'c:\arquivo6.txt';
  try
     HTTP := TIdHTTP.Create(nil);
     POSTData := TIdMultipartFormDataStream.Create;

     for i:= 0 to Length(arquivos) do
        if fileexists (arquivos[i]) then
        begin
           //showmessage(arquivo[i]);
           POSTData.AddFile('userfile[]', arquivos[i], 'multipart/form-data');
           HTTP.Post('http://localhost/ENVIO/up.php', POSTData);
        end;
  finally
     POSTData.Free;
  end;
end;

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

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