Return 从 php 到 dropzone.js 的错误

Return error from php to dropzone.js

我想return处理上传的php代码中的一个案例错误。

目前,如果 php 上传失败,JS 仍然认为它成功了,我认为这是因为它 return 没问题。

我已经尝试 returning false 而不是字符串,但它仍然运行 this.on('success') 函数。

PHP

public function imageUpload(){
    //Сheck that we have a file

    if((!empty($_FILES["file"])) && ($_FILES['file']['error'] == 0)) {

      //Check if the file is JPEG image and it's size is less than 350Kb
      $filename = basename($_FILES['file']['name']);
      $ext = substr($filename, strrpos($filename, '.') + 1);

      if (($ext == "jpg") && ($_FILES["file"]["type"] == "image/jpeg") && 
        ($_FILES["file"]["size"] < 3500000)) {

        //Determine the path to which we want to save this file
          $newname = '/home/anglicvw/public_html/newdev/app/templates/default/images/testimages/'.$filename;
          //Check if the file with the same name is already exists on the server

          if (!file_exists($newname)) {

            //Attempt to move the uploaded file to it's new place
            if ((move_uploaded_file($_FILES['file']['tmp_name'],$newname))) {
               echo "It's done! The file has been saved as: ".$newname;
            } else {
               echo "Error: A problem occurred during file upload!";
            }
          } else {
             echo "Error: File ".$_FILES["file"]["name"]." already exists";
          }
      } else {
         echo "Error: Only .jpg images under 350Kb are accepted for upload";
      }
    } else {
     echo "Error: No file uploaded";
    }
}

JS

$(document).ready(function(){

            Dropzone.autoDiscover = false;

            var myDropzone = new Dropzone('div#imagesdropzone', { url: '/admin/imageUpload',
            parallelUploads: 100,
            maxFiles: 100,});
        });

        Dropzone.options.imagesdropzone = {
            init: function() {
                this.on('success', function( file, resp ){
                  console.log( file );
                  console.log( resp );
                });
                this.on('error', function( e ){
                  console.log('erors and stuff');
                  console.log( e );
                });
            }
        };

this.on('success') 从哪里获取有关(内部)PHP 上传过程的 success/failure 的信息?

我从 HTTP header 的状态代码猜测,即使上传失败也是 200(正常)(它只是打印一些错误文本)。 上传失败建议设置500header

是的,没错。您必须设置 HTTP Header。 看看:

https://github.com/enyo/dropzone/wiki/FAQ#how-to-show-an-error-returned-by-the-server

如果您遇到 HTTP 错误并希望在 DropzoneJS 的悬停错误消息中显示它,您可以:

myDropzone.on("error", function(file, message, xhr) {
    var header = xhr.status+": "+xhr.statusText;
    $(file.previewElement).find('.dz-error-message').text(header);
  });

(该代码 [$().find();] 需要 jQuery)

另一种方法是 return 通过 PHP 发送 JSON 错误消息:

//define text for error message
$output['error'] = 'No Token';

//return right HTTP code
if( $error ){
    http_response_code (401);
}
else{
    http_response_code (200);
}

//set Content-Type to JSON
header( 'Content-Type: application/json; charset=utf-8' );
//echo error message as JSON
echo json_encode( $output );

使用下面的 php 代码片段

public function imageUpload(){
    //Сheck that we have a file

    if((!empty($_FILES["file"])) && ($_FILES['file']['error'] == 0)) {

      //Check if the file is JPEG image and it's size is less than 350Kb
      $filename = basename($_FILES['file']['name']);
      $ext = substr($filename, strrpos($filename, '.') + 1);

      if (($ext == "jpg") && ($_FILES["file"]["type"] == "image/jpeg") && 
        ($_FILES["file"]["size"] < 3500000)) {

        //Determine the path to which we want to save this file
          $newname = '/home/anglicvw/public_html/newdev/app/templates/default/images/testimages/'.$filename;
          //Check if the file with the same name is already exists on the server

          if (!file_exists($newname)) {

            //Attempt to move the uploaded file to it's new place
            if ((move_uploaded_file($_FILES['file']['tmp_name'],$newname))) {
               echo "It's done! The file has been saved as: ".$newname;
            } else {
               header('Error: A problem occurred during file upload!', true, 500);
               //echo "Error: A problem occurred during file upload!";
            }
          } else {
            header("Error: File ".$_FILES["file"]["name"]." already exists", true, 500);
             //echo "Error: File ".$_FILES["file"]["name"]." already exists";
          }
      } else {
        header("Error: Only .jpg images under 350Kb are accepted for upload", true, 500);
         //echo "Error: Only .jpg images under 350Kb are accepted for upload";
      }
    } else {
      header("Error: No file uploaded", true, 500);
     //echo "Error: No file uploaded";
    }
}