搜索
首页后端开发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

TOOPTIMIZEPHPCODEFORDUSEMEMORYUSAGEAGEAGEAGEAGEAGEANDEXECUTITIEM,关注台词:1)USEREEREFERESCENCENCINCOPYINSTEADOFCOPYINGINATATASTRUCTURESTROUCTURESTOREDUCEMORYCONSUMPTION.2)杠杆phphppphpphp'sbuilt intimpunctionslikearray_mapforfunctionslikearray_mapforfforfforfforfasterapasterexecution.3)

PHP电子邮件:分步发送指南PHP电子邮件:分步发送指南May 09, 2025 am 12:14 AM

phpisusedforsendendemailsduetoitsignegrationwithservermailservicesand andexternalsmtpproviders,自动化notifications andMarketingCampaigns.1)设置设置yourphpenvironcormentswironmentswithaweberswithawebserverserverserverandphp,确保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

phperformancetuningiscialbecapeitenhancesspeedandeffice,whatevitalforwebapplications.1)cachingwithapcureduccureducesdatabaseloadprovesrovesponsemetimes.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

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )专业的PHP集成开发工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)