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

时间:2017-03-20 15:14:14

标签: javascript php jquery ajax slim

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

后端应该发回一个json对象。使用该特定图像,它会触发jquery ajax上载的“失败”承诺。 当我记录'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 );
    }
}

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

enter image description here

1 个答案:

答案 0 :(得分:0)

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

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