php+iframe實現無重新整理上傳檔案例子

來源:互聯網
上載者:User

使用label的for屬性來取代js的event轉移,解決IE下“SCRIPT5: 拒絕訪問”的問題;

html代碼

 代碼如下 複製代碼

<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
// 當前上傳對象
var _current    = null;
// 上傳回調方法
function onUploadSuccess(info){
    // 控制台調試,可能是因為console沒定義導致IE無法使用此功能
    typeof console.dir!=='undefined' && console.dir(info);
    // 上傳成功
    if(typeof info.status!=='undefined' && typeof info.path!=='undefined' && info.status==1 && info.path!=''){
        // 改變圖片src,實現即時預覽
        if(_current.find('img').size()>0)
            _current.find('img:eq(0)').prop('src', info.path);
        else
            _current.html('<img src="'+info.path+'" width="100%" height="100%" />');
        // 返回
        return;
    }
    // 上傳失敗則提示錯誤資訊
    alert(info.info);
    // 返回
    return;
}
$(function(){
    $('label[for]').click(function(){
        _current    = $(this);
        $('.uploadform')[0].reset();
    });
    $('.uploadform input:file').change(function(){
        $(this).parent().submit();
    });
});
</script>
</head>
<body>
 
<label for="photo1" style="border:1px solid #CCC; padding:2px; width:120px; height:80px; display:block;"></label>
<label for="photo1" style="border:1px solid #CCC; padding:2px; width:120px; height:80px; display:block;"></label>
 
<form style="display:none;" class="uploadform" action="{:U('upload?callback=window.parent.onUploadSuccess')}" method="post" enctype="multipart/form-data" target="uploadiframe">
    <input type="file" name="photo1" id="photo1" />
    <iframe style="display:none;" name="uploadiframe"></iframe>
</form>
 
</body>
</html>

php處理常式

 代碼如下 複製代碼

<?php
$retval = array('status'=>0, 'info'=>'', 'path'=>'');
if(/*upload success*/){
    $retval['status'] = 1;
    $retval['path'] = 'somepath';
}else{
    $retval['info'] = 'someerror';
}
echo "<script>{$_GET['callback']}(".json_encode($retval).");</script>";
exit;

簡單總結:這個其實很簡單在表單中我們action設定為上傳php的模板檔案,然後我們再在表單target 開啟檔案設定為iframe的name即可。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.