JavaScript 以Json 形式上載檔案到PHP

簡介

先將檔案轉為BASE64編碼,然後再以JSON形式傳送到PHP作處理。

HTML部份

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JSON UPLOAD FILE</title>

    <script src="script.js"></script>
</head>
<body>
    <h1>Json upload file sample</h1>

    <input type="file" name="upload_file" id="upload_file">
    <input type="button" value="Upload" onclick="upload();">
</body>
</html>

JavaScript部份

JavaScript
function upload() {
    let myFile = document.querySelector("#upload_file");

    let base64Data = "";

    if (myFile.value != '') {
        const promise = new Promise((resolve, reject) => {
            if (myFile.files[0] != null) {
                const reader = new FileReader();
                reader.readAsDataURL(myFile.files[0]);
                reader.onload = function (e) {
                    // 將檔案轉成 base64data 格式
                    base64Data = reader.result.split(',')[1];
                    resolve();
                };
                reader.onerror = function (error) {
                    reject(error);
                }
            }
            else {
                resolve();
            }
        });

        promise.then(() => {
            const data = JSON.stringify({
                "file": base64Data
            });

            fetch("upload.php", {
                "method": "post",
                "body": data
            }).then(response => {
                return response.json();
            }).then(response => {
                console.log(response);
            });
        });
    }
}

PHP部份

PHP
<?php
$data = json_decode(file_get_contents('php://input'), true);

if (isset($data['file'])) {
    $file = $data['file'];

    // 設定上載的位置
    $path = "upload_file/";

    if (!file_exists($path)) {
        mkdir($path, 0777, true);
    }

    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mimeType = $finfo->buffer(base64_decode($file));
    $extension = explode('/', $mimeType)[1];
    $fileName = rand(0, 10000) . '.' . $extension; // 將檔案名稱設為 隨機數字加檔案格式
    $path .= $fileName;

    $file = base64_decode($file);
    file_put_contents($path, $file);

    echo json_encode([
        "result" => "success",
    ]);
}

效果示範

開始在上面輸入您的搜索詞,然後按回車進行搜索。按ESC取消。

返回頂部