使用AJAX和PHP上传文件会产生未知错误(BIF jQuery插件)

时间:2015-01-21 05:39:39

标签: php jquery ajax twitter-bootstrap

对我来说,几乎没有比AJAX + PHP更难的事情......但我并没有放弃。

今天我发现了一个很棒的插件,它允许我使用jQuery AJAX和PHP(Krajee Bootstrap FileInput)很好地上传文件,但我无法弄清楚是什么导致了这个错误:

这是HTML代码:

<input id="escanneo" type="file" name="ticket[]" accept="image/*">
<div id="errorBlock43" class="help-block"></div>

jQuery脚本:

$(document).ready(function() {
$("#escanneo").fileinput({
    //showPreview: false,
    browseClass: "btn btn-danger btn-block",
    showCaption: false,
    showRemove: false,
    showUpload: false,
    previewFileType: "image",
    browseLabel: " Subir ticket escanneado",
    browseIcon: '<i class="glyphicon glyphicon-picture"></i>',
    allowedFileExtensions: ["jpg", "JPG", "jpeg", "JPEG", "png", "PNG", "pdf"],
    elErrorContainer: "#errorBlock43",
    msgInvalidFileExtension: 'El formato de "{name}" es incorrecto. Solo archivos "{extensions}" son admitidos.',
    //AJAX
        dropZoneEnabled: false,
        uploadAsync: false,
        uploadUrl: "subir.php", // your upload server url
        uploadExtraData: function() {
            return {
                server: $("input[name='server']").val(),
                user: $("input[name='user']").val()
            };
        }
});

});

upload.php文件

<?php 
// upload.php de http://webtips.krajee.com/ajax-based-file-uploads-using-fileinput-plugin/
if (empty($_FILES['ticket'])) {
    return; // or process or throw an exception
}

// get the files posted
$ticket = $_FILES['ticket'];

// get server posted
$server = empty($_POST['server']) ? '' : $_POST['server'];

// get user name posted
$user = empty($_POST['user']) ? '' : $_POST['user'];

// a flag to see if everything is ok
$success = null;

// file paths to store
$paths= [];

// loop and process files
for($i=0; $i < count($ticket); $i++){
    $ext = explode('.', basename($ticket['name'][$i]));
    $target = "tickets/" . md5(uniqid()) . "." . array_pop($ext);
    if(move_uploaded_file($ticket['tmp_name'][$i], $target)) {
        $success = true;
        $paths[] = $target;
    } else{
        $success = false;
        break;
    }
}

// check and process based on successful status 
if ($success === true) {
    // call the function to save all data to database
    // code for the following function `save_data` is not 
    // mentioned in this example
    save_data($userid, $username, $paths);

    // store a successful response (default at least an empty array). You
    // could return any additional response info you need to the plugin for
    // advanced implementations.
    $output = [];
} elseif ($success === false) {
    $output = ['error'=>'Error while uploading ticket. Contact the system administrator'];
    // delete any uploaded files
    foreach ($paths as $file) {
        unlink($file);
    }
} else {
    $output = ['error'=>'No files were processed.'];
}

// return a json encoded response for plugin to process successfully
echo json_encode($output);
?>

和文件结构(subir.php = upload.php):

enter image description here

如果它有用,这是我的php错误日志:

[21-Jan-2015 06:34:53 Europe/Paris] PHP Warning:  move_uploaded_file(/tickets/cebcea25d53b5708b9e4612fd9871284.png): failed to open stream: No such file or directory in C:\wamp\www\character-empower\subir.php on line 26

[21-Jan-2015 06:34:53 Europe/Paris] PHP Stack trace:

[21-Jan-2015 06:34:53 Europe/Paris] PHP   1. {main}() C:\wamp\www\character-empower\subir.php:0

[21-Jan-2015 06:34:53 Europe/Paris] PHP   2. move_uploaded_file() C:\wamp\www\character-empower\subir.php:26

[21-Jan-2015 06:34:53 Europe/Paris] PHP Warning:  move_uploaded_file(): Unable to move 'C:\wamp\tmp\php195F.tmp' to '/tickets/cebcea25d53b5708b9e4612fd9871284.png' in C:\wamp\www\character-empower\subir.php on line 26

[21-Jan-2015 06:34:53 Europe/Paris] PHP Stack trace:

[21-Jan-2015 06:34:53 Europe/Paris] PHP   1. {main}() C:\wamp\www\character-empower\subir.php:0

[21-Jan-2015 06:34:53 Europe/Paris] PHP   2. move_uploaded_file() C:\wamp\www\character-empower\subir.php:26

您可以在此处下载并测试我为此问题制作的“精简版”:https://drive.google.com/file/d/0Bw5fBW4Q-fJQNHlGNXB6azNTRkE/view?usp=sharing

某处应该有一些语法错误!我无法弄明白...

非常感谢任何提示/帮助!

2 个答案:

答案 0 :(得分:2)

您上传的目录需要是可读/可写的并且应该存在。看来你在Windows上使用它,文件夹分隔符很重要。

在代码中使用DIRECTORY_SEPARATOR而不是代码中使用正斜杠(因此它可以在windows或unix / linux web服务器平台上运行):

$target = "tickets" . DIRECTORY_SEPARATOR . md5(uniqid()) . "." . array_pop($ext);

已更新in the webtip。 BTW祝你好运using my plugin

答案 1 :(得分:0)

您正在尝试将文件移动到服务器内的/tickets/文件夹。因为文件夹以/开头,所以它是绝对路径。

如果您要将文件上传到tickets/替换的同一位置的upload.php文件夹:

$target = "/tickets/" . md5(uniqid()) . "." . array_pop($ext);

$target = "tickets/" . md5(uniqid()) . "." . array_pop($ext);

现在,它将使用upload.php所在的文件夹作为基础文件夹查找相对路径。