php+ajax上传文件或者图片(支持非ie浏览器)

1、编写index.html

<!DOCTYPE html>
<html>
<head>
    <title>Upload Files using XMLHttpRequest - Minimal</title>
    <script type="text/javascript" src="js/upload.js"></script>
</head>
<body>
  <form name="form1" enctype="multipart/form-data" method="post" action="upload.php">
    <div class="row">
      <label for="fileToUpload">Select a File to Upload</label><br />
      <input type="file" name="fileToUpload" id="fileToUpload" οnchange="fileUpload('fileToUpload','form1','fileid');"/>
    </div>
    <div id="fileName"></div>
    <div id="fileSize"></div>
    <div id="fileType"></div>
    <div id="progressNumber"></div>
    文件路径:<input type="text" name="fileid" id="fileid" value="" />
  </form>
</body>
</html>

2、编写upload.php

<?php
	//获取文件后缀名
	function getExt($filename){
		$array = explode('.', $filename);
		$ext = array_pop($array);
		return strtolower($ext);
	}

	//随机数
	function randStr($length){
		$chars="0123456789abcdefghijklmnopqrstuvwxyz"; //字符串
		$string="";
		for($i=0;$i<$length;$i++){
			$string.=substr($chars, rand(0,strlen($chars)-1),1);
		}
		return $string;
	}
	
	function upFile(){
		$files=&$_FILES['fileToUpload'];
		//print_r($_FILES);exit;
		if(!empty($files) && !is_uploaded_file($files['tmp_name'])){
			return $this->status_data(-1,null,"未上传文件");
		}
		//print_r($this->datas);exit;

		$ext=getExt($files['name']);
		
		$imgExt=array('jpg','png','jpeg','gif');
		if(in_array($ext,$imgExt)){
			$cun='upload/picture/'.date('Y-m-d').'/';
		}else{
			$cun='upload/attach/'.date('Y-m-d').'/';
		}
		if(!is_dir($cun)){
			mkdir($cun);
		}
		
		$t=time().randStr(6);
		$file_ext=substr($files['name'],strrpos($files['name'],'.'));
		$fiename=$t.$file_ext;
		$putPath=$cun.$fiename;
		
		$rs = move_uploaded_file($files['tmp_name'],$putPath);//上传图片
		if($rs){
			echo  $_POST['fileid']."|".$putPath;
		}else{
			echo  "error";
		}
	}
	
	upFile();
	
?>

3、引用js

function fileUpload(filename,formname,fileid) {
  var file = document.getElementById(filename).files[0];
  if (file) {
    var fileSize = 0;
    if (file.size > 1024 * 1024)
      fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
    else
      fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
    document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
    document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
    document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
    var fd = new FormData(document.forms.namedItem(formname));
    fd.append("fileid", fileid);//返回时的图片显示在哪个div id里面
    var xhr = new XMLHttpRequest();
    xhr.upload.addEventListener("progress", uploadProgress, false);
    xhr.addEventListener("load", uploadComplete, false);
    xhr.addEventListener("error", uploadFailed, false);
    xhr.addEventListener("abort", uploadCanceled, false);
    xhr.open(document.forms.namedItem(formname).method, document.forms.namedItem(formname).action);
    xhr.send(fd);
  }
}

function uploadProgress(evt) {
  if (evt.lengthComputable) {
    var percentComplete = Math.round(evt.loaded * 100 / evt.total);
    document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
  }
  else {
    document.getElementById('progressNumber').innerHTML = 'unable to compute';
  }
}

function uploadComplete(evt) {
  if(evt.target.responseText){
    var imageres = evt.target.responseText;
    var imagearr = imageres.split("|");
    var imageid = imagearr[0];
    var imageurl = imagearr[1];
    document.getElementById(imageid).value = imageurl;
  }
}

function uploadFailed(evt) {
  document.getElementById('error').innerHTML = 'Error';
}

function uploadCanceled(evt) {
  document.getElementById('abort').innerHTML = 'Canceled';
}


对ie支持不是很好,js高手可自行修改兼容。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现vue+ajax+php的多图片上传并回显,可以按照以下步骤进行: 1.在前端使用Vue的上传组件,设置multiple属性为true,允许用户上传多张图片。 2.在上传组件的change事件中获取用户选择的图片文件,使用FormData对象将图片文件封装成表单数据。 3.使用axios或其他网络请求库将表单数据发送到服务器端。 4.在服务器端接收到表单数据后,解析出图片文件并保存到服务器的指定文件夹中。 5.将图片文件的URL返回给前端,用于回显图片。 下面是一个简单的示例代码: 前端代码: ```html <template> <div> <input type="file" ref="fileInput" @change="handleUploadChange" multiple> <button @click="uploadImages">上传图片</button> <div v-if="imageUrls.length > 0"> <div v-for="imageUrl in imageUrls" :key="imageUrl"> <img :src="imageUrl" style="width: 200px; height: 200px;"> </div> </div> </div> </template> <script> import axios from 'axios' export default { data () { return { imageFiles: [], imageUrls: [] } }, methods: { handleUploadChange () { this.imageFiles = Array.from(this.$refs.fileInput.files) }, uploadImages () { const formData = new FormData() this.imageFiles.forEach(file => { formData.append('images[]', file) }) axios.post('/api/upload_images.php', formData) .then(response => { this.imageUrls = response.data.imageUrls }) .catch(error => { console.log(error) }) } } } </script> ``` 后端代码(使用PHP): ```php <?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { $imageUrls = []; $uploadDir = '/path/to/upload/folder/'; foreach ($_FILES['images']['error'] as $key => $error) { if ($error === UPLOAD_ERR_OK) { $tmpName = $_FILES['images']['tmp_name'][$key]; $fileName = basename($_FILES['images']['name'][$key]); $uploadPath = $uploadDir . $fileName; move_uploaded_file($tmpName, $uploadPath); $imageUrls[] = '/upload/' . $fileName; } } header('Content-Type: application/json'); echo json_encode(['imageUrls' => $imageUrls]); } ``` 在上面的示例代码中,使用了PHP的$_FILES变量来获取上传图片文件。通过遍历$_FILES['images']['error']数组,可以判断每个文件是否上传成功。如果上传成功,将文件移动到指定的上传目录中,并将文件的URL保存到$imageUrls数组中。最后,将$imageUrls数组以JSON格式返回给前端,用于回显图片。 需要注意的是,上传文件时需要确保服务器端的上传目录有写入权限,否则会导致上传失败。同时,需要对上传的文件进行安全性检查,防止上传恶意文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值