form里面文件上传并预览
其实form里面是不能嵌套form的,如果form里面有图片上传和其他input框,我们希望上传图片并预览图片,然后将其他input框填写完毕,再提交整个表单的话,有两种方式!
方式一:点击上传按钮的链接弹出上传页面,上传文件,上传完毕再返回表单页面;这种比较简单,其实就是表单页面的上传按钮仅仅是一个链接,仅用于打开上传文件的弹出页面;
方式二:就是表单里面有<input type="file" name="picture"/>,点击上传按钮后,会在上传按钮旁边有图片预览,这种其实图片也没有上传到服务器,而是将图片做了个本地预览,当填写完其他input框内容,提交后才开始上传的!
其完整代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
<script type= "text/javascript" src= "jquery-3.2.1.js" ></script> <script type= "text/javascript" > function showImg(obj){ var objUrl = getObjectURL(obj.files[0]); if (objUrl) { $(obj).before( '<img src="' + objUrl + '" alt="" width="100px;"> ' ); } } function getObjectURL(file) { var url = null ; if (window.createObjectURL!=undefined) { url = window.createObjectURL(file) ; } else if (window.URL!=undefined) { url = window.URL.createObjectURL(file) ; } else if (window.webkitURL!=undefined) { url = window.webkitURL.createObjectURL(file) ; } return url ; } </script> //文件上传表单 <form method= "post" action= "index.php" enctype= "multipart/form-data" > <input name= "picture" id= "picture" style= "position:absolute;clip:rect(0 0 0 0);" onchange= "showImg(this);" type= "file" > <label style= "cursor:pointer;width:80px;height:30px;text-align:center;line-height:30px;color:#FFFFFF;box-shadow: 2px 2px 2px #888888;" for = "picture" >上传LOGO</label> <input name= "sub" type= "submit" value= "提交" /> </form> //文件上传php代码 <?php $file = @ $_FILES [ 'picture' ]; //得到传输的数据 //得到文件名称 $name = $file [ 'name' ]; $type = strtolower ( substr ( $name , strrpos ( $name , '.' )+1)); //得到文件类型,并且都转化成小写 $allow_type = array ( 'jpg' , 'jpeg' , 'gif' , 'png' ); //定义允许上传的类型 //判断文件类型是否被允许上传 if (!in_array( $type , $allow_type )){ //如果不被允许,则直接停止程序运行 return ; } //判断是否是通过HTTP POST上传的 if (! is_uploaded_file ( $file [ 'tmp_name' ])){ //如果不是通过HTTP POST上传的 return ; } $upload_path = "D:/now/" ; //上传文件的存放路径 //开始移动文件到相应的文件夹 if (move_uploaded_file( $file [ 'tmp_name' ], $upload_path . $file [ 'name' ])){ return $upload_path . $file [ 'name' ]; } else { echo "Failed!" ; } ?> |