Is it possible to capture the origin of a dragged file from the computer?

Asked

Viewed 67 times

1

I wanted to send the image path from the "drop event":

Javascript:

window.onload = function() {

    var dropZone = document.getElementById('box_paper');

    function handleFileSelect(event) {
        event.stopPropagation();
        event.preventDefault();
        event.stopImmediatePropagation();
        dropZone.classList.add('is-dragging');

       var form = $('#upload'); 

       // **************************************************************
        var items  = event.dataTransfer.items;      // -- Items
       //SÓ PRECISO PEGAR A ORIGEM DO ARQUIVO, NÃO O BASE64 DA IMAGEM
       //E COLOCAR NO INPUT FILE...
       //MODELO 1 (comentado por aí) = ISSO NÃO FUNCIONOU... ???? ******
        for (var i = 0; i < items.length; i++) {
            // Get the dropped item as a 'webkit entry'.
            var entry = items[i].webkitGetAsEntry();

            console.log('items',items[i]);

            // Get the same dropped item, but as a File.
            var file = items[i].getAsFile();

            console.log(file);

            if (entry.isDirectory) {

                //ISSO SERIA O PATH DA IMAGEM SENDO ATRIBUIDO NO FORMULÁRIO, #SOQUENAO
                form.find('[file]').attr('value', file.path);
            }
        }

        // **************************************************************

        //MODELO 2 (comentado por aí) = ISSO TAMBÉM NÃO... ???? ****
         var files = event.target.files || event.dataTransfer.files;
          //ISSO SERIA O PATH DA IMAGEM SENDO ATRIBUIDO NO FORMULÁRIO, #SOQUENAO
         form.find('[file]').attr('value', files[0].path);
        // **************************************************************


        // var form = $('#upload'); 

        // var reader = new FileReader();

        // reader.onload = function (event) {
        //     console.log('target', event.target.result);
        //     form.find('[file]').attr('value', event.target.result);
        // };

        // reader.readAsDataURL(files[0]);

          var progress = $('.progress');
          var bar = $('.progress-bar');
          var percent = $('.percent');
          var status = $('#error_display_op1');

          var options = {
              dataType: 'json',
              type:'post',
              resetForm:true,
              clearForm:true,
              beforeSend: function () {
                  $scope.enableSelectionShapes();
                  $('#moldal_progress').modal("show");
                  //cadastrarAlunosNaTurma();
                  progress
                      .removeClass('hide')
                      .show();
                  status.empty();
                  var percentVal = '0%';
                  bar.width(percentVal);
                  percent.html(percentVal);
              },
              uploadProgress: function (event, position, total, percentComplete) {
                  var percentVal = percentComplete + '%';
                  bar.attr('aria-valuenow', percentComplete);
                  bar.width(percentVal);
                  percent.html(percentVal);
                  //
              },
              success: function () {
                  var percentVal = '100%';
                  bar.width(percentVal);
                  percent.html(percentVal);
                  $('#moldal_progress').modal("hide");
              },
              complete: function (xhr, errors, frm) {
                //  console.log(xhr);
                  // $(input).val('');
                  if (xhr.responseJSON) {
                      if (xhr.responseJSON.status) {

                          var file = xhr.responseJSON.filename;
                          var dir = xhr.responseJSON.directory;

                          if (angular.isDefined(file)) {
                              var data = dir + file;


                              fabric.Image.fromURL(data, function (img) {
                                  img.scaleToWidth(200);
                                  img.scaleToHeight(200);

                                  if ($scope.is_mobile) {
                                      var left = 80, top = 80;
                                  } else {
                                      var left = 380, top = ($scope.canvasShape.getHeight() / 2) - 150;
                                  }
                                  img.set({
                                      left: left,
                                      top: top,
                                      angle: 0
                                  });

                                  var oImg = img;


                                  $scope.canvasShape.add(oImg).renderAll();
                                  var a = $scope.canvasShape.setActiveObject(oImg);
                                  var dataURL = $scope.canvasShape.toDataURL({
                                      format: 'png',
                                      multiplier: 4
                                  });
                              });


                          } else {
                              loadingOff();
                              status.empty();
                              var percentVal = '0%';
                              bar.width(percentVal);
                              percent.html(percentVal);
                              $rootScope.toastMessage("danger", "Erro de envio", xhr.responseJSON, 4000);

                          }
                      } else {
                          loadingOff();
                          // status.empty();
                          $rootScope.toastMessage("danger", "Erro de envio", "Não foi possível processar este arquivo.", 4000);


                          var percentVal = '0%';
                          bar.width(percentVal);
                          percent.html(percentVal);
                      }
                  }
              }
          };

          form.ajaxSubmit(options);
      }

      function handleDragOver(evt) {
        dropZone.classList.remove('is-dragging');
        evt.stopPropagation();
        evt.preventDefault();
        evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
      }


  ['dragenter', 'dragover'].forEach(function(e){
    dropZone.addEventListener(e, handleDragOver, false)
  });

  ['dragleave', 'drop'].forEach(function(e){
    dropZone.addEventListener(e, handleFileSelect, false)
  });

}

PHP Zend 1.12:

1) Controller:

public function uploadAutoriaAction()
{

    $postData = $this->apiPutData();
    $request = $this->getRequest();

    if (!empty($postData->token)) {
        if (!empty($postData->csrf_token)) {
            $request->setParam('csrf_token', $postData->csrf_token);
        }
        $request->setParam('token', $postData->token);

    }

    $filterAccessXSSOrigin = new Application_Model_Filter_XSSSecurityAccessOrigin(__FUNCTION__);
    $checkOrigin = $filterAccessXSSOrigin->accessControlAllowOrigin();
    if ($checkOrigin) {
        header("Access-Control-Allow-Origin: $checkOrigin");
        $this->authenticateJson($request);
    }
    $params = $request->getParams();

    $srvApi = new Application_Model_Service_GerenciarUploads();
    $upload = new Zend_File_Transfer_Adapter_Http();
    $result = $srvApi->uploadAutoria($upload);

    echo Zend_Json::encode($result);

}

2) Model:

public function uploadAutoria($upload)
{

    try {

        $size = 8388608; //8MB
        $megas = ($size / 1024 / 1024) . 'MB';
        $directory = $this->folder_imgs_autoria;

        $extensions = 'jpg,jpeg,png,gif';

        $permission_ext = explode(',', $extensions);
        $upload->setDestination($directory);
       // $upload->addFilter('LowerCase', null, 'arquivo');
        $upload->addValidator('Size', false, $size);
        $upload->addValidator('Extension', false, $extensions);
        $originalFilename = $upload->getFileName(null, false);
        $upload->clearFilters();

        $files = $upload->getFileInfo();

        $ext = strrchr($upload->getFileName(), '.');

        $filename = 'autoria_image_' .rand(0, 9999999999) . $ext;

        if (file_exists($upload->getFileName())) {
            throw new Zend_File_Transfer_Exception("Ocorreu um erro de duplicidade, tenter enviar novamente o arquivo.");
        }

        if ($upload->getFileSize() > $size) {
            throw new Zend_File_Transfer_Exception("O tamanho do arquivo é muito grande, não deve exceder o limite de {$megas}.");
        }
        $extension_file = str_replace('.', '', $ext);
        if (!in_array($extension_file, $permission_ext)) {
            throw new Zend_File_Transfer_Exception("O formato do arquivo não é suportado.");

        }
        $upload->addFilter('Rename', 'large_'.$filename, $upload->getFileName());
        // This takes care of the moving and making sure the file is there

        $date = new \DateTime();

        if (!$upload->receive()) {
            $messages = $upload->getMessages();
            $throw = implode("\n", $messages);
            throw new Zend_File_Transfer_Exception($throw);
        }

        //resize image
        $status = $this->resizeImage($directory . 'large_'.$filename, $directory . $filename,  723, 723);

        if ($status) {
            //remove o arquivo maior
            if(file_exists($directory . 'large_'.$filename)) {
                unlink($directory . 'large_'.$filename);
            }
        }


        $arrayInfo = array(
            'original_file' => $originalFilename,
            'data_upload' => $date->format('d/m/Y H:i:s'),
            'url_file' => $upload->getFileName(null, false),
            'message' => 'Arquivo enviado com sucesso!',
            'filename' => $filename,
            'directory' => '/'. FOLDER_ADM . '/uploader/files/autoria/imgs/',
            'type' => 'image_autoria',
            'status' => true
        );

    } catch (Zend_File_Transfer_Exception $e) {
        $arrayInfo = array(
            'status' => false,
            'message' => $e->getMessage()
        );
    }

    return $arrayInfo;
}

Obs: No doubt, it’s bigger than an XY problem, I want the X, but the X doesn’t seem to be a valid path, I mean, I need to find a solution... As this way does not work, because it would be a security failure to have access to the file, there must be another alternative, because what I need in the end is to send the file to the server (after releasing it on the screen).

One way that I was trying to do is inherit a method that was already functional where I click a button under a hidden form, which I send the file to my editing area, through a simple upload form, ajax, does the rest of the effects from that click, when the image receives through the "change" event, "loading" occurs with a progress CSS, etc. Which in turn, is displayed when the image file has not yet been loaded, the idea is to capture this same event, when an image is dragged into my editing area, and save this link with the same renamed file features that will be saved to the server...

  • The source you cite would be the image path on the user’s computer?

  • Exact @Andersoncarloswoss, I wanted to grab the image path when dropping the file...

  • So it’s not possible. That would be a major security breach for exposing information from the user’s computer. Why do you need this?

  • To upload the file, and have its address on the server. It cannot be Base64... I need to have it as a file.

  • To upload does not need to know the origin, the moment you drag to the browser it takes care of what is needed. Why you need to know which is the file path on the user if the upload will be done on the server?

  • I don’t need to know, I just need to put it in the form input in ajax and send as file type...

  • In thesis, I could even create it on the server by saving this Base64 as a file, but I need to recover it and save in the same format that I upload.

  • 1

    That’s a XY problem, Uploading files via drag'n'drop does not work that way, nor does file input accept paths. The file upload path is a simple view to make the user’s life easier. It would be important [Dit] the problem reflecting the real need, not the way you think it would work.

  • So the problem is to upload when dropping the file on the page? If so, I don’t see why to put the PHP part into the question. You can limit it to being able to do the HTTP request that sends the file with Javascript through drag-n-drop events. If the PHP side is also not working as it should, maybe it would be a question for another question.

  • Actually, php is only there to show how it gets the file. Because there must be ways to treat in php and send Base64, convert and save this file in the folder I believe.

Show 5 more comments
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.