Ajax 上传失败但无法捕获任何错误

Ajax upload failing but impossible to catch any errors

我使用前端 jquery ajax 脚本将图像发送到 php 后端脚本,该后端脚本由 slim 框架应用程序托管。 该过程适用于除单个图像(已附)之外的所有图像。

后端应该发回一个 json 对象。使用该特定图像,它会触发 jquery ajax 上传的 'fail' 承诺。 当我登录 'errorThrown' 时,我得到:

SyntaxError: JSON Parse error: Unrecognized token '<'

我得到这个可能是因为返回的数据不是 json 而是 html。它只用一张图像来做仍然是不合理的。我无法在此过程中发现任何错误。

我认为这里的目标是知道错误是什么。如果您有建议作为查找链中错误的方法,请指教。

前端上传脚本:

$( function() {
    let idOfUploadedImage = null
    let maxAllowedImages  = 5


    // Use case: User clicks on the 'Upload your image' button: image is sent to the server.
    $( '.imageUploader' ).on( 'click', function( event ) {
        event.preventDefault();

        // determine which image (field) is currently treated
        idOfUploadedImage = event.target.id

        let form     = $( '.blog-form' );
        let formdata = (window.FormData) ? new FormData( form[ 0 ] ) : null;
        let data     = (formdata !== null) ? formdata : form.serialize();


        $.ajax( {
            url        : '/image-attachment/upload-image',
            type       : form.attr( 'method' ),
            contentType: false, // obligatoire pour de l'upload
            processData: false, // obligatoire pour de l'upload
            dataType   : 'json', // selon le retour attendu
            data       : data
        } ).done( function( response ) {
            console.log( `Upload image success: ${idOfUploadedImage}` )
            console.log( response )
            console.log( numberOfImagesVisibleFieldsOnTheForm )

            // Store in corresponding hidden fieldpath of uploaded image as returned from server.
            $( `#path-${idOfUploadedImage}` ).val( response.path );

            // In case an image was sucessfully uploaded, we make sure the image count that determines
            // the number of image container to show stays sync.
            numberOfImagesVisibleFieldsOnTheForm++

            // Show thumbnail of uploaded file
            let field         = form.find( `input[name="${idOfUploadedImage}"]` );
            let files         = field[ 0 ].files;
            let image         = files[ 0 ];
            let $imagePreview = $( `#image-preview-${idOfUploadedImage}` ).show();
            $imagePreview.find( 'img' ).attr( 'src', window.URL.createObjectURL( image ) );


            // Check if we can still ad images. If so, show next image elements.
            if ( numberOfImagesVisibleFieldsOnTheForm > maxAllowedImages ) {
                console.log( "You can't add more images" )
            } else {
                $( `#container-image-${numberOfImagesVisibleFieldsOnTheForm}` ).show()
            }

        } ).fail( function( xhr, textStatus, errorThrown ) {
            console.log( errorThrown );
            // Reset field from which image caused the error
            resetUploadImageField( idOfUploadedImage )

            //if ( response.responseJSON && response.responseJSON.error ) {
            //    alert( response.responseJSON.error );
            //}
        } ).always( function() {
            console.log( "Upload image process complete" );
        } );
    } );
} )

后端脚本:

 namespace Rib\Src\Apps\ImageAttachment\ImageAttachmentControllers;

use Rib\Src\Apps\ImageAttachment\ImageAttachmentModel;
use Slim\Http\Request;
use Slim\Http\Response;


class UploadImage
{
    /**
     * Use case: user has clicked to upload via ajax a single image from the frontend. This is NOT
     * the entire blog post form submission.
     * @param Request $request
     * @param Response $response
     * @return Response
     */
    public function upload( Request $request, Response $response )
    {
        $imageModel = new ImageAttachmentModel();

        # Create image in temp dir. Return its information
        $tmpImageInfo = $imageModel->uploadImageInTempDir();

        # If there are any error with the image (not an image, too big....) treat the error
        $error = $tmpImageInfo[ 'error' ] ?? null;
        if ( $error ) {
            # Inform the frontend with error message
            return $response->withJson( $tmpImageInfo, 500 );
        }

        # Resize image and create its thumbnails in tmp directory
        $tmpImageInfo = $imageModel->resizeImageAndCreateThumbnails(
            $tmpImageInfo[ 'tmpSaveTargetPlusImageName' ],
            $tmpImageInfo[ 'imageNameWithoutExtension' ],
            $tmpImageInfo[ 'imageOriginalExtension' ] );


        // At this point array $tmpImageInfo = "201703/e-1490022600.jpg"


        # We pass back to the frontend the final path of the image which will be in the form of:
        # 'yearmonth/filename-random.ext' . Note that currently image is NOT in its final
        # destination. It will have to be moved there when user finally posts the full form.
        return $response->withJson( $tmpImageInfo );
    }
}

图片罪魁祸首: 编辑:当我从 Whosebug 中抓取图像时,上传与图像一起工作,但不是我计算机上的原始图像。我尝试重命名它并在本地移动它:它不起作用。

这是一个 'exif_read_data(e-1490024361.jpg): Illegal IFD size'。问题发生在非常具体的图像上。我有一个全局异常处理程序,但我无法得到错误,因为 post ajax 调用你无法在屏幕上呈现任何内容。正如所建议的那样,我能够通过阅读浏览器网络实用程序中的响应文本来了解它。

然后我从我的异常和错误处理程序中排除了对这个特定错误的处理,并且脚本能够 运行 正常。