Maison > Article > développement back-end > Comment prévisualiser les images en php
PHP代码(推荐学习:PHP视频教程)
<?php header("Content-type:text/html;charset=utf-8"); $upFile = $_FILES['file']; /** * 创建文件夹函数,用于创建保存文件的文件夹 * @param str $dirPath 文件夹名称 * @return str $dirPath 文件夹名称 */ function creaDir($dirPath){ $curPath = dirname(__FILE__); $date = date('Y-m-d',time()); $path = $curPath.'\\'.$dirPath.'\\'.$date; if (is_dir($path) || mkdir($path,0777,true)) { return $dirPath; } } //判断文件是否为空或者出错 if ($upFile['error']==0 && !empty($upFile)) { $dirpath = creaDir('upload1'); $filename = iconv("utf-8","gbk",$_FILES['file']['name']); $date = date('Y-m-d',time()); $queryPath = './'.$dirpath.'/'.$date.'/'.$filename; // 判断上传的是不是图片 if($_FILES['file']['type'] == 'image/jpeg' || $_FILES['file']['type']=='image/jpg'){ //move_uploaded_file将浏览器缓存file转移到服务器文件夹 if(move_uploaded_file($_FILES['file']['tmp_name'],$queryPath)){ $filename = iconv("utf-8","utf-8",$_FILES['file']['name']); $queryPath = './'.$dirpath.'/'.$date.'/'.$filename; echo $queryPath; } } } ?>
解决上传的图片文件名中文乱码:
$filename = iconv("utf-8","gbk",$_FILES['file']['name']);
解决无法预览的问题:
$filename = iconv("utf-8","utf-8",$_FILES['file']['name']);
html代码
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>上传图片</title> <script src="./js/jquery-1.10.2.min.js"></script> <script type="text/javascript"> $(function(){ $('div').css('color','red'); $("#up").click(function() { //formdata储存异步上传数据 var formData = new FormData($('form')[0]); formData.append('file',$(':file')[0].files[0]); //坑点: 无论怎么传数据,console.log(formData)都会显示为空,但其实值是存在的,f12查看Net tab可以看到数据被上传了0 $.ajax({ url:'./upload.php', type: 'POST', data: formData, //这两个设置项必填 contentType: false, processData: false, success:function(data){ // console.log(data) var srcPath = data; //console.log(111); //注意这里的路径要根据自己的储存文件的路径设置 $('.picDis img').attr('src',srcPath); } }) }); }); </script> </head> <body> <form enctype="multipart/form-data" id="upForm"> <input type="file" name="file" ><br><br> <input type="button" value="提交" id="up"> </form> <div class="picDis"> <img src="" alt=""> </div> </body> </html>
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!