javascript – 从php返回错误到dropzone.js
作者:互联网
我想从我处理上传的PHP代码中返回一个错误.
目前,如果php上传失败,JS仍然认为它成功了,我认为这与它返回的事实有关.
我试过返回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 );
});
}
};
解决方法:
是的这是对的.您必须设置HTTP标头.
看一下:
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);
});
(你需要jQuery代码[$().find();])
另一种方法是通过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 );
标签:javascript,php,dropzone-js 来源: https://codeday.me/bug/20190824/1705733.html