当前位置: 首页 > news >正文

原生JavaScript+PHP多图上传实现

摘要

很多场景下需要选择多张图片上传,或者是批量上传以提高效率,多图上传的需求自然就比较多了,本文使用最简单的XMLHttpRequest异步上传图片。

界面

在这里插入图片描述

上传示例

在这里插入图片描述

代码

index.html

<!DOCTYPE html>
<html><head><title>多图上传</title><meta charset="utf-8"><style>#fileInput{width: 500px;height: 45px;margin: 50px auto 0;background: #eee;display: block;padding: 20px 20px;border-radius: 20px;}#previewContainer{width: 500px;margin: 10px auto;background: #eee;padding: 20px 20px;display: none;}.preview-image {max-width: 200px;max-height: 200px;margin-bottom: 10px;}</style></head><body><!--选择文件--><input type="file" id="fileInput" accept="image/*" multiple><div id="previewContainer"></div><script>const fileInput = document.getElementById('fileInput');const previewContainer = document.getElementById('previewContainer');// 监听选择文件fileInput.addEventListener('change', handleFileSelect);function handleFileSelect(event) {const files = event.target.files;for (let i = 0; i < files.length; i++) {const file = files[i];const reader = new FileReader();reader.onload = function(event) {const image = document.createElement('img');image.className = 'preview-image';image.src = event.target.result;previewContainer.appendChild(image);// 将文件上传至服务器uploadImage(file);}reader.readAsDataURL(file);}}// 将文件上传至服务器function uploadImage(file) {const xhr = new XMLHttpRequest();const formData = new FormData();// 将文件添加到formData对象formData.append('image', file);// 设置XHR请求的处理函数xhr.onreadystatechange = function() {if (xhr.readyState === XMLHttpRequest.DONE) {if (xhr.status === 200) {console.log('上传成功');// 显示图片预览区域document.querySelector('#previewContainer').setAttribute('style', 'display:block');// 打印JSONconsole.log(JSON.parse(xhr.response))} else {console.log('上传失败');}}}// 发送POST请求到服务器xhr.open('POST', 'upload.php', true);xhr.send(formData);}</script></body>
</html>

upload.php
(请建立一个upload文件夹以存放上传的文件)

<?php// 编码header("Content-type:application/json");// 检查是否有文件上传if (isset($_FILES['image'])) {// 获取上传的文件信息$file = $_FILES['image'];// 获取文件名$fileName = $file['name'];// 获取文件的临时路径$tmpFilePath = $file['tmp_name'];// 指定保存目录$uploadDir = 'upload/';// 验证是否为图片文件if ((($_FILES["image"]["type"] == "image/gif")|| ($_FILES["image"]["type"] == "image/jpeg")|| ($_FILES["image"]["type"] == "image/jpg")|| ($_FILES["image"]["type"] == "image/pjpeg")|| ($_FILES["image"]["type"] == "image/x-png")|| ($_FILES["image"]["type"] == "image/png"))&& ($_FILES["image"]["size"] < 10485760)){// 生成唯一的文件名$uniqueFileName = uniqid() . '_' . $fileName;// 拼接保存路径$uploadPath = $uploadDir . $uniqueFileName;// 获取HTTP协议function get_http_type(){$http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';return $http_type;}// 将临时文件移动到目标路径if (move_uploaded_file($tmpFilePath, $uploadPath)) {// 上传成功// 可以在此处进行进一步处理,比如生成缩略图、添加水印等$result = array('code' => 200,'msg' => '上传成功','url' => get_http_type().dirname($_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']).'/'.$uploadPath);} else {// 上传失败$result = array('code' => 202,'msg' => '文件上传失败');}}else{// 不合规的文件$result = array('code' => 202,'msg' => '不合规的文件');}} else {// 没有文件上传$result = array('code' => 202,'msg' => '没有选择要上传的文件');}// JSONecho json_encode($result, JSON_UNESCAPED_UNICODE);
?>

作者

TANKING

http://www.lryc.cn/news/160523.html

相关文章:

  • 企业架构LNMP学习笔记30
  • 数学建模算法汇总(全网最全,含matlab案例代码)
  • openpnp - 底部相机高级矫正后,底部相机看不清吸嘴的解决方法
  • 怎么提高自己当众讲话的能力?
  • 孙哥Spring源码第20集
  • 【计算机网络】HTTP(上)
  • Maven学习记录
  • H5游戏开发H5休闲小游戏定制H5软件定制
  • Spring基础及IoC容器的理解
  • 护网行动为什么给的钱那么多
  • 软考知识汇总-计算机系统
  • OpenCV 11(图像金字塔)
  • Linux学习笔记-Ubuntu系统用户、群组、权限管理
  • 文章预览 安防监控/视频存储/视频汇聚平台EasyCVR播放优化小tips
  • Nand Flash的特性及烧录问题
  • 【React 】useLayoutEffect 和 useEffect的区别
  • oracle数据库常见的优化步骤与脚本
  • 并发内存池(C++)
  • 本地起一个VUE 前端项目
  • Python爬虫:Selenium的介绍及简单示例
  • 每日刷题|回溯法解决全排列问题第二弹之解决字符串、字母大小排列问题
  • python循环遍历字典: title_content_list.append([key, value])print(ti
  • Redis List类型命令 - Set类型命令 - SortedSet类型命令
  • 等级保护 —— 安全控制点,安全要求
  • nginx-缓存
  • layui使用富文本已经使用第三方插件Kz.layedit来优化layui的富文本
  • 某公司二面面试题总结
  • Ubuntu编译运行socket.io
  • h5开发网站-页面内容不够高时,如何定位footer始终位于页面的最底部
  • 手机也可以搭建个人博客?安卓Termux+Hexo搭建属于你自己的博客网站【cpolar实现公网访问】