上传图片、图片回显、后台接收图片并保存

1 篇文章 0 订阅

一、上传图片、实现图片数据回显

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- 引用jQuery 使用CDN加速 -->
    <script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<style>
    /* 限制图片的大小 */
    #avatar{
        width: 200px;
    }
    /* 隐藏上传图片的按钮 */
    #changeImg {
        display: none;
    }
</style>

<body>
    <!-- 
        使用 "multipart/form-data" 编码类型提交表单数据。这种编码类型允许在表单中包含文件上传字段。
     -->
    <form method="post" enctype="multipart/form-data">
        <label>头像:</label><br />
        <!-- 通过使用点击label来触发input的点击事件,来选择要上传的文件 -->
        <label for="changeImg">
            <img id="avatar" src="./imgs/upload.png">
        </label>
        <!-- 如需要上传多个文件要将name中的 "img" 改为 "img[]" 也就是加一个中括号; 代表我上传的可能是多个文件,用数组保存。 -->
        <input type="file" id="changeImg" name="img"><br />

        <!-- 提交按钮 -->
        <input type="submit" value="上传">
    </form>
</body>
<script>
    $("#changeImg").change(function() {
        // 获取当前文件(一个对象,含有该文件的相关信息)
        file = $(this)[0].files[0];

        // 封装一个返回file的url
        function getObjectURL(file) {
            var url = null;
            if (window.createObjectURL != undefined) { // basic
                url = window.createObjectURL(file);
            } else if (window.URL != undefined) { // mozilla(firefox)
                url = window.URL.createObjectURL(file);
            } else if (window.webkitURL != undefined) { // webkit or chrome
                url = window.webkitURL.createObjectURL(file);
            }
            return url;
        }
        // 返回对象地址
        var url = URL.createObjectURL(file);
        // 把图像更新
        $('#avatar').attr('src', url);
    })
</script>

</html>

二、后台接收单张图片,并保存

<?php
if ($_POST) {
    // 保存图片的路径
    $dirPath = './imgs/';

    // 允许文件格式
    $fileType = ['image/gif', 'image/pjpeg', 'image/jpeg', 'image/png'];

    // 判断保存图片的文件夹是否存在,不存在就创建
    if (!is_dir($dirPath)) {
        mkdir($dirPath, 0777, true);
    }

    // 传过来的文件使用$_File接收
    /* array(5) { 
        ["name"]=> string(14) "甜甜 (2).jpg" 
        ["type"]=> string(10) "image/jpeg" 
        ["tmp_name"]=> string(22) "C:\Windows\php7DC6.tmp" 
        ["error"]=> int(0) ["size"]=> int(153160)
     } */
    // var_dump($_FILES['img']);

    // 判断文件类型
    // echo $_FILES['img']['type']; // image/jpeg
    if (!in_array($_FILES['img']['type'], $fileType)) {
        echo "文件类型错误!";
        exit;
    }

    // 判断文件是否是通过 HTTP POST 上传的
    if (!is_uploaded_file($_FILES['img']['tmp_name'])) {
        echo "文件上传方式错误!";
        exit;
    }

    // 判断上传过程中出现的其他错误,这里统统处理为错误
    echo $error;
    if ($error == UPLOAD_ERR_OK) {
        // 图片临时地址(暂存区)
        $tmp_name = $_FILES['img']['tmp_name'];
        // 获取图片后缀名
        // explode将字符串以 "." 作为分割符进行切割,用数组存储
        $ext_name = explode('.', $_FILES['img']['name'])[1];
        // 自定义 文件保存时的 文件名 + 后缀名
        $nfname = date('YmdHis') . mt_rand(100, 999) . "." . $ext_name;
        // 自定义 文件路径 + 文件名 + 后缀名
        $fPath = $dirPath . $nfname;
        // 将图片从 暂存区 保存到 文件夹中(或服务器中)
        move_uploaded_file($tmp_name, $fPath);
        // 输出或返回文件路径(用于在数据库中保存)
        echo $fPath;
    } else {
        echo "文件上传失败";
        exit;
    }
}

三、接收单张图片

<?php 
    if($_POST['uploadpic'] == "上传"){
        $dirPath = './images/';
        $imgPathArr = [];
        $fileType = ['image/gif','image/pjpeg','image/jpeg','image/png'];
        if(!is_dir($dirPath)){
            mkdir($dirPath,0777,true);
        }
        // var_dump($_FILES['imgs']);
        foreach($_FILES['imgs']['error'] as $key => $error){
            // 判断文件类型
            if(!in_array($_FILES['imgs']['type'][$key],$fileType)){
                echo "<script>alert('文件类型错误!')</script>";
                exit;
            }
            // 判断文件是否是通过 HTTP POST 上传的
            if(!is_uploaded_file($_FILES['imgs']['tmp_name'][$key])){
                echo "<script>alert('文件上传方式错误!')</script>";
                exit;
            }
            // 判断上传过程中出现的错误
            if($error == UPLOAD_ERR_OK){
                $tmp_name = $_FILES['imgs']['tmp_name'][$key];
                $ext_name = explode('.',$_FILES['imgs']['name'][$key])[1];
                $nfname = date('YmdHis').mt_rand(100,999).".".$ext_name;
                $fPath = $dirPath.$nfname;
                move_uploaded_file($tmp_name, $fPath);
                $imgPathArr[] = $fPath;
            }else{
                echo "<script>alert('文件上传失败')</script>";
                exit;
            }
        }
        echo '<script>history.go(-1);</script>';
    }
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>多张图片上传</title>
</head>
<body>
    <form method="post" enctype="multipart/form-data">
        <input type="file" multiple name="imgs[]">
        <input type="submit" name="uploadpic" value="上传">
    </form>
</body>
</html>
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小超爱编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值