ajax和php返回json异常



我试图在本地Web服务器中上传一个文件,但遇到了一个我不完全理解的错误。我想我的PHP脚本可能有问题。这是我的代码:

JS:

addImageBlobHook: (blob, callback) => {
let formData = new FormData();
// file in a 'multipart/form-data' request
formData.append(0, blob, blob.name);
fetch('upload', {
method: 'POST',
body: formData
}).then(response => {
if (response.ok) {
return response.json();
}
throw new Error('Server or network error');
}).then(response => {
if (!response.success) {
throw new Error('Validation error');
}
callback(response.data.url, 'alt text');
}).catch(error => {
console.log(error);
})
}

PHP:

<?php

if(isset($_FILES['file']['name'])){
// file name
$filename = $_FILES['file']['name'];

// Location
$location = 'upload/'.$filename;

// file extension
$file_extension = pathinfo($location, PATHINFO_EXTENSION);
$file_extension = strtolower($file_extension);

// Valid extensions
$valid_ext = array("jpg","png","jpeg");

$response = 0;
if(in_array($file_extension,$valid_ext)){
// Upload file
if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
$response = 1;
}
}

echo $response;
exit;
}
else echo json_encode(2);

我得到以下错误:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

第85行,在我的代码中是JS文件中的console.log(error);

编辑:

用isset($_FILES(替换isset($_FILES([文件…..(允许输入"if"并生成vardump,如下所示:

if(isset($_FILES)){
var_dump($_FILES);

哪个返回:

C:wamp64wwwtoastupload.php:5:
array (size=1)
0 => 
array (size=5)
'name' => string 'Beer_mug_transparent.png' (length=24)
'type' => string '' (length=0)
'tmp_name' => string '' (length=0)
'error' => int 3
'size' => int 0

您只是回显响应。这并没有给出正确的回应。请参阅更新的php代码。

<?php
if(isset($_FILES['file']['name'])){
// file name
$filename = $_FILES['file']['name'];
// Location
$location = 'upload/'.$filename;
// file extension
$file_extension = pathinfo($location, PATHINFO_EXTENSION);
$file_extension = strtolower($file_extension);
// Valid extensions
$valid_ext = array("jpg","png","jpeg");
$response = 0;
if(in_array($file_extension,$valid_ext)){
// Upload file
if(move_uploaded_file($_FILES['file']['tmp_name'],$location)){
$response = 1;
}
}
echo json_encode($response);
exit;
}

相关内容

  • 没有找到相关文章

最新更新