成果

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' => '此类文件不能上传'    );}// 输入JSONecho json_encode($result, JSON_UNESCAPED_UNICODE);?>

留神,须要在同一目录下建设upload目录以寄存上传的文件。

作者

TANKING