搜尋
首頁後端開發php教程利用ajax+php實現文件上傳

利用ajax+php實現文件上傳

Apr 12, 2018 am 09:14 AM
ajaxphp文件上傳

理論上此類的文件/圖片上傳插件已經很多了,但是在使用的過程中還是會遇到各種各樣的問題,兼容問題、後台問題~~等等,所以既然別人的輪子我用不好,那就自己做一個吧。

本文使用jq.ajax和php實作上傳功能,前端程式碼一般無差,有的小夥伴後台不是php的,請參考貴語言的文檔進行操作即可。

先看效果圖,整個上傳介面大概是這樣的:看demo

 

整體想法:

1、建立input設定type=file,id=file,樣式設定opacity:0,position:absolute

2、建立遮罩層,並設定position:absolute並且z-index大於file

3、建立FormData對象,把file放到FormData中做成資料

4、建立ajax,發送FormData資料到upload.php,監聽ajax的progress事件,即時返回上傳進度

5、在html頁面輸出伺服器的回應

6、上傳完成之後,點選「繼續上傳」按鈕,開啟檔案選擇框,可繼續上傳。

HTML部分,比較簡單:


<p class="upload"> <p class="uploadBox">
    <span class="inputCover">选择文件</span>
	<form enctype="">
	    <input type="file" name="file" id="file" />
	    <button type="button" class="submit">上传</button>
	</form>
	<button type="button" class="upagain">继续上传</button>
	<span class="processBar"></span>
	<span class="processNum">未选择文件</span>
    </p>
</p>

CSS,樣式可以依照個人喜好自由調整,這裡僅供參考:

*{
    font-family: &#39;microsoft yahei&#39;;
    color: #4A4A4A;
}
.upload{
    width: 700px;
    padding: 20px;
    border: 1px dashed #ccc;
    margin: 100px auto;
    border-radius: 5px;
}
.uploadBox{
    width: 100%;
    height: 35px;
    position: relative;
}
.uploadBox input{
    width: 200px;
    height: 30px;
    background: red;
    position: absolute;
    top: 2px;
    left: 0;
    z-index: 201;
    opacity: 0;
    cursor: pointer;
}
.uploadBox .inputCover{
    width: 200px;
    height: 30px;
    position: absolute;
    top: 2px;
    left: 0;
    z-index: 200;
    text-align: center;
    line-height: 30px;
    font-size: 14px;
    border: 1px solid #009393;
    border-radius: 5px;
    cursor: pointer;
}
.uploadBox button.submit{
    width: 100px;
    height: 30px;
    position: absolute;
    left: 230px;
    top: 2px;
    border-radius: 5px;
    border: 1px solid #ccc;
    background: #F0F0F0;
    outline: none;
    cursor: pointer;
}
.uploadBox button.submit:hover{
    background: #E0E0E0;
}
.uploadBox button.upagain{
    width: 100px;
    height: 30px;
    position: absolute;
    left: 340px;
    top: 2px;
    display: none;
    border-radius: 5px;
    border: 1px solid #ccc;
    background: #F0F0F0;
    outline: none;
    cursor: pointer;
}
.uploadBox button.upagain:hover{
    background: #E0E0E0;
}
.processBar{
    display: inline-block;
    width: 0;
    height: 7px;
    position: absolute;
    left: 500px;
    top: 14px;
    background: #009393;
}
.processNum{
    position: absolute;
    left: 620px;
    color: #009393;
    font-size: 12px;
    line-height: 35px;
}

JS部分,jq.ajax:

$(document).ready(function(){
    var inputCover = $(".inputCover");
    var processNum = $(".processNum");
    var processBar = $(".processBar");
    //上传准备信息
    $("#file").change(function(){
        var file = document.getElementById(&#39;file&#39;);
        var fileName = file.files[0].name;
	var fileSize = file.files[0].size;
        processBar.css("width",0); 
        //验证要上传的文件
	if(fileSize > 1024*2*1024){
	    inputCover.html("<font>文件过大,请重新选择</font>");
	    processNum.html(&#39;未选择文件&#39;);
	    document.getElementById(&#39;file&#39;).value = &#39;&#39;;
	    return false;
	}else{
	    inputCover.html(fileName+&#39; / &#39;+parseInt(fileSize/1024)+&#39;K&#39;);
	    processNum.html(&#39;等待上传&#39;);
	}
    })

    //提交验证
    $(".submit").click(function(){
	if($("#file").val() == &#39;&#39;){
            alert(&#39;请先选择文件!&#39;);
	}else{
	    upload();
	}
    })

    //创建ajax对象,发送上传请求
    function upload(){
        var file = document.getElementById(&#39;file&#39;).files[0];
	var form = new FormData();
	form.append(&#39;myfile&#39;,file);
	$.ajax({
	    url: &#39;upload.php&#39;,//上传地址
	    async: true,//异步
	    type: &#39;post&#39;,//post方式
	    data: form,//FormData数据
	    processData: false,//不处理数据流 !important
 	    contentType: false,//不设置http头 !important
 	    xhr:function(){//获取上传进度            
                myXhr = $.ajaxSettings.xhr();
                if(myXhr.upload){
                    myXhr.upload.addEventListener(&#39;progress&#39;,function(e){//监听progress事件
                    var loaded = e.loaded;//已上传
                        var total = e.total;//总大小
                        var percent = Math.floor(100*loaded/total);//百分比
                        processNum.text(percent+"%");//数显进度
                        processBar.css("width",percent+"px");//图显进度}, false);
                }
                return myXhr;
            },
 	    success: function(data){//上传成功回调
 		console.log("文档当前位置是:"+data);//获取文件链接
 		document.cookie = "url="+data;//此行可忽略
 		$(".submit").text(&#39;上传成功&#39;);
 		$(".upagain").css("display","block");
             }
	})
    }

    //继续上传
    $(".upagain").click(function(){
	$("#file").click();
	processNum.html(&#39;未选择文件&#39;);
        processBar.css("width",0); 
        $(".submit").text(&#39;上传&#39;);
	document.getElementById(&#39;file&#39;).value = &#39;&#39;;
	$(this).css("display","none");
    })
})

上傳完畢,upload.php處理檔(為了伺服器安全,僅貼出程式碼片段):

<?php  
if(isset($_FILES["myfile"])){  
    move_uploaded_file($_FILES["myfile"]["tmp_name"],"ajax/".$_FILES["myfile"]["name"]);
    echo "http://www.xuxiangbo.com/ajax/".$_FILES["myfile"]["name"];
}else{
    echo &#39;no file&#39;;
}
?>

轉自部落格

#作者:Imin

連結:http://blog.xuxiangbo.com/im-22.html

我相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

PHP sftp 實作檔案的上傳與下載 

##四種php隨機字產生符串的方法

以上是利用ajax+php實現文件上傳的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
優化PHP代碼:減少內存使用和執行時間優化PHP代碼:減少內存使用和執行時間May 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP電子郵件:分步發送指南PHP電子郵件:分步發送指南May 09, 2025 am 12:14 AM

phpisusedforsendendemailsduetoitsignegrationwithservermailservicesand andexternalsmtpproviders,自動化intifications andMarketingCampaigns.1)設置設置yourphpenvenvironnvironnvironmentwithaweberswithawebserverserververandphp,確保themailfunctionisenabled.2)useabasicscruct

如何通過PHP發送電子郵件:示例和代碼如何通過PHP發送電子郵件:示例和代碼May 09, 2025 am 12:13 AM

發送電子郵件的最佳方法是使用PHPMailer庫。 1)使用mail()函數簡單但不可靠,可能導致郵件進入垃圾郵件或無法送達。 2)PHPMailer提供更好的控制和可靠性,支持HTML郵件、附件和SMTP認證。 3)確保正確配置SMTP設置並使用加密(如STARTTLS或SSL/TLS)以增強安全性。 4)對於大量郵件,考慮使用郵件隊列系統來優化性能。

高級PHP電子郵件:自定義標題和功能高級PHP電子郵件:自定義標題和功能May 09, 2025 am 12:13 AM

CustomHeadersheadersandAdvancedFeaturesInphpeMailenHanceFunctionalityAndreliability.1)CustomHeadersheadersheadersaddmetadatatatatataatafortrackingandCategorization.2)htmlemailsallowformattingandttinganditive.3)attachmentscanmentscanmentscanbesmentscanbestmentscanbesentscanbesentingslibrarieslibrarieslibrariesliblarikelikephpmailer.4)smtppapapairatienticationaltication enterticationallimpr

使用PHP和SMTP發送電子郵件的指南使用PHP和SMTP發送電子郵件的指南May 09, 2025 am 12:06 AM

使用PHP和SMTP發送郵件可以通過PHPMailer庫實現。 1)安裝並配置PHPMailer,2)設置SMTP服務器細節,3)定義郵件內容,4)發送郵件並處理錯誤。使用此方法可以確保郵件的可靠性和安全性。

使用PHP發送電子郵件的最佳方法是什麼?使用PHP發送電子郵件的最佳方法是什麼?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

PHP中依賴注入的最佳實踐PHP中依賴注入的最佳實踐May 08, 2025 am 12:21 AM

使用依賴注入(DI)的原因是它促進了代碼的松耦合、可測試性和可維護性。 1)使用構造函數注入依賴,2)避免使用服務定位器,3)利用依賴注入容器管理依賴,4)通過注入依賴提高測試性,5)避免過度注入依賴,6)考慮DI對性能的影響。

PHP性能調整技巧和技巧PHP性能調整技巧和技巧May 08, 2025 am 12:20 AM

phpperformancetuningiscialbecapeitenhancesspeedandeffice,whatevitalforwebapplications.1)cachingwithapcureduccureducesdatabaseloadprovesrovessetimes.2)優化

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。