美文网首页
PHP 原生开发 商品添加页面 上传文件学习记录

PHP 原生开发 商品添加页面 上传文件学习记录

作者: 无故下架内容so账号已弃用 | 来源:发表于2019-05-19 22:51 被阅读0次

php 上传相关代码准备:

  • html 代码
// html
<form name="publish-form" id="publish-form" action="publish.php" method="post" enctype="multipart/form-data">
  <div class="additem">
    <!-- 使用accept html5属性 声明仅接受png gif jpeg格式的文件                -->
    <label id="for-file">画品</label>
    <input type="file" accept="image/png,image/gif,image/jpeg" id="file" name="file">
  </div>
  <div style="margin-top: 20px">
    <button type="submit">发布</button>
  </div>
</form>

html 中值得注意的是:

  1. form 元素中的 enctype="multipart/form-data", 要确保文件上传表单的属性是 enctype="multipart/form-data",否则文件上传不了。
  2. accept="image/png,image/gif,image/jpeg" 选择文件时过滤掉其他类型的文件
  • jq 代码
// jq
$(function () {
  $('#publish-form').submit(function () {
    var  file = $('#file').val(),
    if (file == '' || file.length <= 0) {
      layer.tips('请选择图片', '#file', {time: 2000, tips: 2});
      $('#file').focus();
      return false;
    }
    return true;
  })
})

修改 php.ini

  1. 设置文件最大上传限制
upload_max_filesize 修改为 20M
  1. 表单允许上传的最大文件大小 post_max_size
post_max_size 修改为 64M

php 上传图片的相关 php 知识点

  • $_FILES[$file]

$file: 为 input 中的 name, 即 file

// php
$file = $_FILES['file'];
print_r($file); 

// 结果:
/*
Array
(
    [name] => index_banner.png
    [type] => image/png
    [tmp_name] => C:\Windows\phpBAA6.tmp
    [error] => 0
    [size] => 249058
)
*/
  1. name: 客户端机器文件的原名称

  2. type: 文件的 MIME 类型,如果浏览器提供此信息的话。

  3. tmp_name: 文件被上传后在服务端储存的临时文件名。

  4. size: 已上传文件的大小,单位为字节。

  5. error: 和该文件上传相关的错误代码

  • is_uploaded_file()

is_uploaded_file ( string $filename ) : bool

$filename: 要检查的文件名。是指 tmp_name 上传后的临时文件名

判断文件是否是通过 HTTP POST 上传的

  • is_dir() 和 mkdir()
  1. is_dir($filename) 如果文件名存在,并且是个目录,返回 TRUE,否则返回FALSE。

  2. mkdir ( string $pathname [, int $mode = 0777 [, bool $recursive = false [, resource $context ]]] ) : bool 新建目录

(a). $pathname 要创建的目录名称

(b). $mode 默认的 mode 是 0777,意味着最大可能的访问权。windows 下忽略

(c). recursive 允许递归创建由 \pathname 所指定的多级嵌套目录。

  • uniqid(), mt_rand()
  1. uniqid() 获取一个带前缀、基于当前时间微秒数的唯一ID。

  2. mt_rand ( int $min , int $max ) : int 生成更好的随机数

  • move_upload_file() 将上传的文件移动到新位置

move_uploaded_file ( string $filename , string $destination ) : bool

$filename
上传的文件的文件名。

$destination
移动文件到这个位置。

返回值:
成功时返回 TRUE。

如果 $filename 不是合法的上传文件,不会出现任何操作,move_uploaded_file() 将返回 FALSE。

如果 $filename 是合法的上传文件,但出于某些原因无法移动,不会出现任何操作,move_uploaded_file() 将返回 FALSE。此外还会发出一条警告。

php 代码

// func.php

/**
 * 文件上传
 * @param $file
 * @return string 返回上传之后的访问地址
 */
function uploadFile($file) {
    // 文件名
    $fileName = $file['name'];
    // 文件类型
//    $fileType = $file['type'];
    // 文件大小
    $fileSize = $file['size'];
    // 临时文件名
    $fileTmpName = $file['tmp_name'];

    // 文件大小判断
    if ($fileSize > 10*1024*1024) {
        redirectMsg('文件大小不能超过 10M!', '0', 'publish.php');
    }

    // 检查文件是否上传成功
    if (!is_uploaded_file($fileTmpName)) {
        redirectMsg('文件上传失败, 请检查后重新提交!', '0', 'publish.php');
    }

    // 访问目录
    $uploadUrl = '/static/upload/';
    // 存放图片的文件夹
    $imgDir = date('Y/md/', $_SERVER['REQUEST_TIME']);
    // 上传目录
    $uploadPath = './static/upload/'.$imgDir;

    if (!is_dir($uploadPath)) {
        // 目录不存在, 创建目录
        mkdir($uploadPath, 0755, true);
    }

    // 文件扩展名
    $extension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
    // 文件名
    $imgName = uniqid().mt_rand(1000,9999).'.'.$extension;
    // 文件类型验证
    if (!in_array($extension, ['jpg', 'png', 'jpeg', 'gif'])) {
        redirectMsg('请上传 .jpg/.jpeg/.png/.gif 类型的文件!', '0', 'publish.pnp');
    }

    // 文件物理地址
    $imgPath = $uploadPath.$imgName;
    // 文件url地址 http://www.gallery.com 为我本地配置的虚拟域名
    $imgUrl = 'http://www.gallery.com'.$uploadUrl.$imgDir.$imgName;

    // 如果上传操作失败, 则需要查看文件夹的访问权限
    if (!move_uploaded_file($fileTmpName, $imgPath)) {
        redirectMsg('上传失败!', '0', 'publish.php');
    }

    return $imgUrl;
}

参考资料: https://class.imooc.com/sc/22

官方资料: https://www.php.net/manual/zh/features.file-upload.php

相关文章

网友评论

      本文标题:PHP 原生开发 商品添加页面 上传文件学习记录

      本文链接:https://www.haomeiwen.com/subject/rgofzqtx.html