【发布时间】:2017-03-21 00:55:17
【问题描述】:
我使用前端 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取回图像时,上传与图像一起工作,但不是我电脑上的原始图像。我尝试重命名并在本地移动它:它不起作用。
【问题讨论】:
-
请发布上传 ajax 调用的响应。问题是从服务器返回的 JSON 不是有效的 JSON。
-
愿意打赌你有一个错误页面而不是返回 JSON,打开网络面板并查看错误是什么。
-
@NirajShah 这有帮助。事实上,我能够在响应文本中看到我设置但由于 ajax 调用而看不到的 catch all exception var dump。事实证明错误是:'exif_read_data(e-1490024361.jpg):非法 IFD 大小'。现在我必须对此进行调查。
-
因为我能够捕捉到错误,您可以提出解决方案作为答案。如果我不能解决 exif 问题,我可能会打开一个新问题。
标签: javascript php jquery ajax slim