Stories

Detail Return Return

fetch異步上傳圖片(附html+JavaScript+php代碼) - Stories Detail

效果

image.png

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>圖片上傳示例</title>
        <meta charset="utf-8">
        <script src="upload.js"></script>
        <style>
            *{
                padding: 0;
                margin: 0;
            }
            #app{
                width: 500px;
                margin: 100px auto 0;
                padding: 20px 20px;
                background: #eee;
                border-radius: 15px;
            }
        </style>
    </head>
<body>
    
    <div id="app">
        <h1>fetch圖片上傳示例</h1>
        
        <!--上傳表單-->
        <input type="file" id="imageFile" accept="image/*">
        
        <!--上傳結果-->
        <div id="result"></div>
    </div>
</body>
</html>

upload.js

// 確保JavaScript代碼在DOM加載完成後執行
document.addEventListener('DOMContentLoaded', function() {
    
    // 獲取點擊上傳的按鈕
    var fileButton = document.getElementById('imageFile');
    
    // 監聽選擇文件按鈕是否已經選擇了文件
    fileButton.addEventListener('change', function (){
        
        // 獲取選擇的文件
        var fileSelected = fileButton.files[0];
        
        // 執行上傳函數
        uploadFile(fileSelected, function(error, response) {
            if (error) {
                
                // 上傳文件失敗
                console.log(error);
            } else {
                
                // 上傳文件成功
                var jsonData = JSON.parse(response);
                
                console.log(jsonData);
                
                // 顯示上傳結果預覽
                document.getElementById('result').innerHTML = '<img src="'+jsonData.url+'" width="350" />';
            }
        });
    });
    
    // 清空file表單的選擇
    fileButton.value = '';
})

// 上傳函數
function uploadFile(file, callback) {
    
    // 獲取表單數據
    var formData = new FormData();
    formData.append('file', file);
    
    // 請求上傳服務器
    fetch('upload.php', {
        method: 'POST',
        body: formData,
    })
    .then(function(response) {
        return response.text();
    })
    .then(function(data) {
        callback(null, data);
    })
    .catch(function(error) {
        callback(error, null);
    });
}

upload.php

<?php
// 編碼
header("Content-type:application/json");
 
// 獲取文件
$file = $_FILES["file"]["name"];
 
// 獲取文件後綴名
$hzm = substr($file,strpos($file,"."));
 
// 設置新文件名
$newfile = date("Y-m-d")."-".rand(100,999);
 
// 允許上傳的後綴
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $file);
$extension = end($temp);

if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 10485760)
&& in_array($extension, $allowedExts)){
    
    // 判斷上傳結果
    if ($_FILES["file"]["error"] > 0){
        
        $result = array(
            'code' => 201,
            'msg' => '上傳失敗'
        );
    }else{
        
        // 上傳文件
        move_uploaded_file($_FILES["file"]["tmp_name"], "upload/".$newfile.$hzm);
        $file_url = 'http://'.$_SERVER['SERVER_NAME'].$_SERVER["REQUEST_URI"];
        $result = array(
            "code" => 200,
            "msg" => "上傳成功",
            "url" => dirname($file_url)."/upload/".$newfile.$hzm
        );
    }
}else{
    
    $result = array(
        'code' => 202,
        'msg' => '此類文件不能上傳'
    );
}

// 輸出JSON
echo json_encode($result, JSON_UNESCAPED_UNICODE);
?>

注意,需要在同一目錄下建立upload目錄以存放上傳的文件。

image.png

作者

TANKING

user avatar dingtongya Avatar kobe_fans_zxc Avatar sunplay Avatar linx Avatar lin494910940 Avatar abc-x Avatar weishiledanhe Avatar xiao2 Avatar leoych Avatar ruanjiankaifa_xiaofanya Avatar god23bin Avatar crmeb Avatar
Favorites 35 users favorite the story!
Favorites

Add a new Comments

Some HTML is okay.