dongtiao0279 2018-08-28 10:41
浏览 70
已采纳

使用Ajax,Jquery的Fileupload

im relatively new to coding, but nevertheless have got a little problem. My main problem basically is that the file I have chosen to upload doesnt end up in the toimport folder on the Server, altough the function shows a success. Please help if you may know a solution to this problem.

The script from Upload_form.php :

<script>
// Wir registrieren einen EventHandler für unser Input-Element (#uploadFile)
// wenn es sich ändert
$('body').on('change', '#uploadFile', function() {
    var data = new FormData(); // das ist unser Daten-Objekt ...
    data.append('file', this.files[0]); // ... an die wir unsere Datei anhängen
    $.ajax({
        url: 'upload.php', // Wohin soll die Datei geschickt werden?
        data: data,          // Das ist unser Datenobjekt.
        type: 'POST',         // HTTP-Methode, hier: POST
        processData: false,
        contentType: false,
        // und wenn alles erfolgreich verlaufen ist, schreibe eine Meldung
        // in das Response-Div
        success: function() { $("#responses").append("Datei erfolgreich hochgeladen");
        }
    });
});
</script>

upload.php

$target_dir = "toimport/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$FileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}

// Allow certain file formats
if($FileType != "xlsx" && $FileType != "xls" && $FileType != "csv"
    && $FileType != "gif" ) {
    echo "Sorry, only XLSX, XLS & CSV files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],     $target_file)) {
    echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
    echo "Sorry, there was an error uploading your file.";
    }
}
  • 写回答

1条回答 默认 最新

  • duanbo6871 2018-08-28 11:01
    关注
    1. You need to write jQuery in $(document).ready(function(){...}) or $(function(){...})
    2. enctype: 'multipart/form-data', to $.ajax
    3. $_FILES["file"] instead of $_FILES["fileToUpload"]

    <!DOCTYPE html>
    <html>
    
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Page Title</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
            crossorigin="anonymous"></script>
        <script>
            $(function () {
                $('body').on('change', '#uploadFile', function () {
                    console.log('asdfsadfa');
                    var file_data = $('#uploadFile').prop('files')[0];
                    var form_data = new FormData();
                    form_data.append('file', file_data);
                    $.ajax({
                        url: "upload.php",
                        type: "POST",
                        data: form_data,
                        contentType: false,
                        cache: false,
                        enctype: 'multipart/form-data',
                        processData: false,
                        success: function (data) {
                            console.log(data);
                            $("#responses").append("Datei erfolgreich hochgeladen");
                        }
                    });
                });
            })
        </script>
    </head>
    
    <body>
        <input type="file" id="uploadFile" />
        <div id="responses"></div>
    </body>
    
    </html>

    PHP Code:

    <?php
    
    $target_dir = "toimport/";
    
    $target_file = $target_dir . basename($_FILES["file"]["name"]);
    $uploadOk = 1;
    $FileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
    
    // Check if file already exists
    if (file_exists($target_file)) {
        echo "Sorry, file already exists.";
        $uploadOk = 0;
    }
    
    // Allow certain file formats
    if ($FileType != "xlsx" && $FileType != "xls" && $FileType != "csv"
        && $FileType != "gif") {
        echo "Sorry, only XLSX, XLS & CSV files are allowed.";
        $uploadOk = 0;
    }
    // Check if $uploadOk is set to 0 by an error
    if ($uploadOk == 0) {
        echo "Sorry, your file was not uploaded.";
    // if everything is ok, try to upload file
    } else {
        if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
            echo "The file ". basename($_FILES["file"]["name"]). " has been uploaded.";
        } else {
            echo "Sorry, there was an error uploading your file.";
        }
    }
    
    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含