图片上传并预览

1                  <td style="width: 60px;display: block;position: absolute;">
2                                     <input type="file"
3                                            style="opacity:0; filter:alpha(opacity=0); height: 40px; width: 40px; position: absolute; top: 0; left: 0; z-index: 9;"
4                                            onchange="handleFiles(this,'{$l.id}')">
5 
6                                     <img src="{$l.image}" style="height: 40px; width: 40px;" id="img_{$l.id}"></td>
 1    function handleFiles(obj, id) {
 2 
 3         file = document.getElementById("img_" + id);
 4 
 5         var files = obj.files;
 6         img = new Image();
 7 
 8         if (window.URL) {
 9             //File API
10             img.src = window.URL.createObjectURL(files[0]); //创建一个object URL,并不是你的本地路径
11             img.onload = function (e) {
12                 window.URL.revokeObjectURL(this.src); //图片加载后,释放object URL
13             }
14         }
15 
16         file.src = img.src;
17         //上传文件
18         var fd = new FormData();//实例化一个表单
19         xhr = new XMLHttpRequest();
20         fd.append('file', files[0]);//追加图片元素
21         xhr.open("post", "upload.php");//请求方式,请求地址
22         xhr.onreadystatechange = function () {
23             if (xhr.readyState == 4) {
24 
25             }
26         };
27         xhr.send(fd);

 

posted @ 2018-01-10 10:47  Fbio  阅读(274)  评论(0)    收藏  举报