0

I am trying to create a upload using the PHP and Javascript by using Jquery-File-Upload Plugin.

Here I have a problem after the Upload.

  1. When I check the data in upload.php by doing print_r the $_Files[upl] data array is showing null for array elements instead of values for names, tmp_name, size except for the error which is showing as 4.
  2. Once after the upload is done the instead of being in the modal displaing the Knob and showing the status it goes to the upload page and displays echo error status in the seperate page.

This is the modal "uploadTaskAttachments.php"

<?php
include dirname(__FILE__) . DIRECTORY_SEPARATOR . '../db/dbconnect.php';
require(dirname(__FILE__) . DIRECTORY_SEPARATOR . "../Login/logincheck.php");




$strHTML = "<div class='modal-dialog' role='document'>
                <div class='modal-content'>
                    <div class='modal-header'>
                        <button type='button' class='close' data-dismiss='modal' aria-label='Close'><span aria-hidden='true'>&times;</span></button>
                        <h4 class='modal-title' id='edit-modal-label'>Upload Attachments</h4>
                    </div>";
                
$strHTML .= "       <form id='taskUpload' method='post' action='upload.php' enctype='multipart/form-data'>
                        <div id='drop'>
                            Drop Here

                            <a>Browse</a>
                            <input type='file' name='upl' multiple />
                        </div>

                        <ul>
                            <!-- The file uploads will be shown here -->
                        </ul>
                    </form> 
                </div>
            </div>";
echo $strHTML;
?>

Javascript

function fnUploadTaskAttachments() {
  $.ajax({
    type: "POST",
    data: {
      "id": task_id
    },
    url: "uploadTaskAttachments.php",
    success: function(data) {
      $("#UploadTaskAttach").html(data);
      $('#UploadTaskAttach').modal({
        backdrop: false
      });
      $('#UploadTaskAttach').modal('show');
      $('#UploadTaskAttach').modal({
        refresh: true
      });
      $('#UploadTaskAttach').draggable({
        handle: ".modal-header"
      });

      $(function() {

        var ul = $('#taskUpload ul');

        $('#drop a').click(function() {
          // Simulate a click on the file input button
          // to show the file browser dialog
          $(this).parent().find('input').click();
        });

        // Initialize the jQuery File Upload plugin
        $('#taskUpload').fileupload({

          // This element will accept file drag/drop uploading
          dropZone: $('#drop'),

          // This function is called when a file is added to the queue;
          // either via the browse button, or via drag/drop:
          add: function(e, data) {
            var tpl = $('<li class="working"><input type="text" value="0" data-width="48" data-height="48"' +
              ' data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" /><p></p><span></span></li>');

            // Append the file name and file size
            tpl.find('p').text(data.files[0].name)
              .append('<i>' + formatFileSize(data.files[0].size) + '</i>');

            // Add the HTML to the UL element
            data.context = tpl.appendTo(ul);

            // Initialize the knob plugin
            tpl.find('input').knob();

            // Listen for clicks on the cancel icon
            tpl.find('span').click(function() {
              if (tpl.hasClass('working')) {
                jqXHR.abort();
              }
              tpl.fadeOut(function() {
                tpl.remove();
              });
            });

            // Automatically upload the file once it is added to the queue
            console.log({
              data
            });
            var jqXHR = data.submit();
          },

          progress: function(e, data) {
            // Calculate the completion percentage of the upload
            var progress = parseInt(data.loaded / data.total * 100, 10);

            // Update the hidden input field and trigger a change
            // so that the jQuery knob plugin knows to update the dial
            data.context.find('input').val(progress).change();
            if (progress == 100) {
              data.context.removeClass('working');
            }
          },
          fail: function(e, data) {
            // Something has gone wrong!
            data.context.addClass('error');
          }
        });

        // Prevent the default action when a file is dropped on the window
        $(document).on('drop dragover', function(e) {
          e.preventDefault();
        });

        // Helper function that formats the file sizes
        function formatFileSize(bytes) {
          if (typeof bytes !== 'number') {
            return '';
          }

          if (bytes >= 1000000000) {
            return (bytes / 1000000000).toFixed(2) + ' GB';
          }

          if (bytes >= 1000000) {
            return (bytes / 1000000).toFixed(2) + ' MB';
          }

          return (bytes / 1000).toFixed(2) + ' KB';
        }
      });
    }
  });
}

Upload.php

 <?php
     $allowed =array('swf', 'bak', 'msg', 'blank');
     if(isset($_FILES['upl']) && $_FILES['upl']['error'] == 0){
     $extension = pathinfo($_FILES['upl']['name'], PATHINFO_EXTENSION);
     if(!in_array(strtolower($extension), $allowed)){
      echo '{"status":"error"}';
      exit;
     }
     if(move_uploaded_file($_FILES['upl']['tmp_name'], $FileServer.$_FILES['upl']['name'])){
      echo '{"status":"success"}';
      exit;
     }
   }
  echo '{"status":"error"}';
  exit;
 ?>

Output enter image description here

Rohit Gowda
  • 41
  • 13
  • Is there anything else in $_FILES at all when you upload, with any name? Would be good if you could post the full dump of it in the question – ADyson Jun 21 '22 at 11:17
  • Hi @ADyson Thank you for the reply, please check the output image you can find values that i am sending – Rohit Gowda Jun 21 '22 at 11:34
  • Ok. Well error 4 means no file was uploaded. Have you checked the Payload for this request? – ADyson Jun 21 '22 at 11:37
  • Also the fact you're seeing this response on the main browser window (as well as in the Networkt tool) suggests the request is maybe not happening via AJAX. Any console errors? Does the request show as XHR or not in the Network tool? Have you used the JS debugger to check if the fileUpload code is actually firing? – ADyson Jun 21 '22 at 11:39
  • Ya the size is showing as 0 but the file is getting uploaded properly. – Rohit Gowda Jun 21 '22 at 11:40
  • Not really sure what you mean by that tbh. What exactly does it show in the payload? – ADyson Jun 21 '22 at 11:42
  • Whe i tried to debug the JS the data is showing properly and on " var jqXHR = data.submit();" the data is getting submitted properly with all values. – Rohit Gowda Jun 21 '22 at 11:46
  • Ok. So again, what exactly does it show in the payload tab? – ADyson Jun 21 '22 at 11:55
  • And as an aside, have you looked into why other people have had problems with error 4 (no file uploaded)? e.g. https://stackoverflow.com/questions/8394423/troubleshooting-file-upload-error-code-4, https://stackoverflow.com/questions/21698253/php-upload-file-yields-error-code-4-why, https://www.google.com/search?q=php+upload+error+4 etc. Might be something relevant in those. – ADyson Jun 21 '22 at 11:59
  • Hi, in payload it just shows "upl: (binary)" I have tried many things also trying to pass value through ajax in submit bu still loads the whole upload page. – Rohit Gowda Jun 21 '22 at 12:03
  • You need to check tmpname on path info and it is not right way to process, extension can be changed. And error 4 is no files. – JoelCrypto Jun 21 '22 at 12:05
  • Thank you ADyson and JoelCrypto for your replies, I changed javascript in the add and updated with the Ajax and it is working fine now. I used this https://stackoverflow.com/questions/39202691/ajax-file-uploading-to-php-file-gives-error-4 method instead of data.sumbit. – Rohit Gowda Jun 21 '22 at 12:48

0 Answers0