title: INSERT BASE64 FILE INTO ORACLE BLOB USING PHP
body: <p>I’m trying to save images as BLOB on my ORACLE 11g R2 database through the base64 of files uploaded, but when i retrieve this file from DB, it dont show the a image with base64_encode function. And when i dowload this file from SQL Developer, the file doesn’t the image as well, only a message saying that the image is invalid or is corrupted. Details of my problem below:
  I have this form in my web page:
  <a href="http://i.stack.imgur.com/6JBoD.png" rel="nofollow">Upload Page 1</a></p>
  
  <p>The “+” button is a file input that when clicked, the user can choose one or more files to upload and these files are showed on a preview, as you can see below:
  <a href="http://i.stack.imgur.com/j8Vte.png" rel="nofollow">Upload Page 2</a></p>
  
  <p>The user can open file input, selecet how many images he wants, close file input and re-open it to add more files how many times he wants. For each file added, a javascript create the preview and set the base64 in href of “a” element, as below:</p>
  
  <pre><code>    //create preview
  $("#exams-fileinput").on('change',function(e){
      var input = $(this);
      var files = input.prop('files');
      var countFiles = files.length;//alert(files.length);
  
      if (window.File &amp;&amp; window.FileReader){ 
          var allow = /png|jpg|jpeg|tiff|pdf$/i;
          // com suporte a FileReader()
          for(i= 0;i &lt;countFiles; i++){                
              file = files[i]; 
              if(!allow.test(file.name)){continue;}
              imageType = /image.*/;
              reader = new FileReader();
              reader.onload = function(e){
                  filePreview = e.target;
                  var fileName    = file.name;
                  var fileResult  = filePreview.result;
                  var fileThumb   = file.type.match(imageType) ? fileResult : 'assets/img/file-document.png'; // https://cdn4.iconfinder.com/data/icons/office-20/128/OFFice-51-256.png assets/img/file-document.png
                  var classIframe = file.type.match(imageType) ? '' : 'fancybox.iframe';
                  var imgPrevContent =  
                          '&lt;div name="file-added" class="col-xs-6 col-sm-4 col-md-3 ms-file-thumbnail-preview-item" &gt;'+ '&lt;a href="'+fileResult+'" class="ms-filedata fancybox '+classIframe+'" rel="exam" data-type="img" data-file-name="'+fileName+'"&gt;'+ //&lt;= aqui vai entrar o "fancybox.iframe", se necessário &lt;= Vamos obter daqui o código do arquivo para subir ".ms-filedata"
                                  '&lt;figure class="img-responsive img-thumbnail" style="background-image:url('+fileThumb+');"&gt;'+ 
  
                                      '&lt;figcaption&gt;'+
                                          '&lt;p&gt;&lt;i class="fa fa-eye fa-3x"&gt;&lt;/i&gt;&lt;p&gt;'+
                                          '&lt;p class="ms-ellipsis"&gt;'+fileName+'&lt;/p&gt;'+
                                      '&lt;/figcaption&gt;'+
                                  '&lt;/figure&gt;'+
                              '&lt;/a&gt;'+
                              '&lt;input type="file" value="'+fileResult+'" id="" style="display: none;"&gt;'+
                          '&lt;/div&gt;';
  
   console.log('Nome do arquivo: '+fileName+' - Tamanho: '+ file.size+' - HTML: '+imgPrevContent.length);
                fileName='';
                  $("#exam-view-files").append(imgPrevContent);
              };                
              reader.readAsDataURL(file);
          }            
      }else{ 
          // browser doesn't supor file reader
      }
  });
  </code></pre>
  
  <p>When users click on save button “Salvar”, i take all bases64 of files added and sent by ajax to save in a BLOB field in my ORACLE 11g R2 database as below:</p>
  
  <pre><code>//save function
  $("#btn-save-files").click(function(e){
      var filesToAdd = [];
  
      $("div[name=file-added]").each(function(e){
          filesToAdd.push({
                             content: $(this).children("a").attr("href"),
                             name: $(this).children("a").data("file-name")
                          });
      });
  
      $.ajax({
              type: 'POST',
              url: 'controller/ctrl-person-profile-action.php',
              data: { action: "insertfiles", 
                      files: filesToAdd
                      },
              datatype: "json",
              async: true,
              success: function(response){
                  response = JSON.parse(response);
                  switch(response["status"].toLowerCase()){
                      case "success": swal("Pronto", "Adicionado com sucesso", "success");
                          break;
                      case "fail": swal("Atenção", response["message"], "warning");
                          break;
                      default: swal("Ops..", "Ocorreu um erro inesperado ao inserir o medicamento", "error");
                          break;
                  }
              }
          });
  }
  </code></pre>
  
  <p>And a take these files and save by PHP, as below:</p>
  
  <pre><code>    //Ajax calls this function
  function InsertFiles(){
  $files = isset($_REQUEST['files']) ? $_REQUEST['files'] : null;
  
  foreach ($files as $file) {
      $fileBase64 = explode(",", explode(";", $file["content"])[1])[1];
      $fileType = explode(":",(explode(";", $file["content"])[0]))[1];
  
      $fileInsert = new MyFileClass();
      $fileInsert-&gt;setFile($fileBase64);
      $fileInsert-&gt;setType($fileType);
      $fileInsert-&gt;Insert();
  }
  
      //Class MyFile method insert:
  public function Insert(){
  $sql = "INSERT FILES (ID,
                                                              MIME_TYPE,
                                                              FILE)
                                                              VALUES(SEQ_FILES.NEXTVAL,
                                                              '$this-&gt;type,
                                                              EMPTY_BLOB()
  ) RETURNING FILE INTO :file";
  
      $conn = GetDBConnection();
      $statment = oci_parse($conn, $sql)
  
      // Creates an "empty" OCI-Lob object to bind to the locator
      $fileBlob = oci_new_descriptor($conn, OCI_DTYPE_LOB);
  
      // Bind the returned Oracle LOB locator to the PHP LOB object
      oci_bind_by_name($statment, ":file", $fileBlob, -1, OCI_B_BLOB);
  
      // Execute the statement using , OCI_DEFAULT - as a transaction
      oci_execute($statment, OCI_DEFAULT)
          or die ("Erro execute SQL command");
  
      // Now save a value to the LOB
      if (!$fileBlob-&gt;save('INSERT: '.base64_decode($this-&gt;file))) {
          // On error, rollback the transaction
          oci_rollback($conn);
          die("Erro execute SQL command");
      } else {
          // On success, commit the transaction
          oci_commit($conn);
      }
  
      // Free resources
      oci_free_statement($statment);
      $fileBlob-&gt;free();
      //feca conexão
      oci_close($conn);
  }
  </code></pre>
  
  <p>Can anyone give me some help to save this base64 file into a BLOB field on ORACLE and retrieve a valid file from my BLOB?</p>
  
  <p>Thx a lot!</p>