原生JS和jQuery版實(shí)現(xiàn)文件上傳功能
更新時間:2016年04月18日 15:19:33 投稿:lijiao
這篇文章主要介紹了HTML5中用js、jQuery結(jié)合Ajax實(shí)現(xiàn)文件上傳功能,HTML5中已經(jīng)可以用Ajax上傳文件了,而且代碼簡單,借助 FormData類即可發(fā)送文件數(shù)據(jù),感興趣的小伙伴們可以參考一下
本文實(shí)例分享了原生JS版和jQuery 版實(shí)現(xiàn)文件上傳功能的例子,供大家參考,具體內(nèi)容如下
<!doctype html>
<html lang="zh">
<head>
<meta charset="utf-8">
<title>HTML5 Ajax Uploader</title>
<script src="jquery-2.1.1.min.js"></script>
</head>
<body>
<p><input type="file" id="upfile"></p>
<p><input type="button" id="upJS" value="用原生JS上傳"></p>
<p><input type="button" id="upJQuery" value="用jQuery上傳"></p>
<script>
/*原生JS版*/
document.getElementById("upJS").onclick = function() {
/* FormData 是表單數(shù)據(jù)類 */
var fd = new FormData();
var ajax = new XMLHttpRequest();
fd.append("upload", 1);
/* 把文件添加到表單里 */
fd.append("upfile", document.getElementById("upfile").files[0]);
ajax.open("post", "test.php", true);
ajax.onload = function () {
console.log(ajax.responseText);
};
ajax.send(fd);
}
/* jQuery 版 */
$('#upJQuery').on('click', function() {
var fd = new FormData();
fd.append("upload", 1);
fd.append("upfile", $("#upfile").get(0).files[0]);
$.ajax({
url: "test.php",
type: "POST",
processData: false,
contentType: false,
data: fd,
success: function(d) {
console.log(d);
}
});
});
</script>
</body>
</html>
php代碼:
<?php
if (isset($_POST['upload'])) {
var_dump($_FILES);
move_uploaded_file($_FILES['upfile']['tmp_name'], 'up_tmp/'.time().'.dat');
//header('location: test.php');
exit;
}
?>
更多精彩內(nèi)容請參考專題《ajax上傳技術(shù)匯總》,《javascript文件上傳操作匯總》和《jQuery上傳操作匯總》進(jìn)行學(xué)習(xí)。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助。
您可能感興趣的文章:
- js 實(shí)現(xiàn) input type="file" 文件上傳示例代碼
- JS文件上傳神器bootstrap fileinput詳解
- 原生JS實(shí)現(xiàn)前端本地文件上傳
- 學(xué)習(xí)使用AngularJS文件上傳控件
- JS簡單實(shí)現(xiàn)文件上傳實(shí)例代碼(無需插件)
- ajaxFileUpload.js插件支持多文件上傳的方法
- 分享5個好用的javascript文件上傳插件
- SpringBoot+Vue.js實(shí)現(xiàn)前后端分離的文件上傳功能
- 基于HTML5+js+Java實(shí)現(xiàn)單文件文件上傳到服務(wù)器功能
- 原生JS實(shí)現(xiàn)文件上傳
相關(guān)文章
jQuery操作Dom元素與遍歷以及JS遍歷詳細(xì)講解
這篇文章主要介紹了jQuery操作Dom元素、jQuery遍歷、JavaScript遍歷,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2023-01-01
jquery之基本選擇器practice(實(shí)例講解)
下面小編就為大家?guī)硪黄猨query之基本選擇器practice(實(shí)例講解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09
jQuery為iframe的body添加click事件的實(shí)現(xiàn)代碼
jQuery為iframe的body添加click事件的實(shí)現(xiàn)代碼,需要的朋友可以參考下。2011-04-04
jQuery+CSS實(shí)現(xiàn)一個側(cè)滑導(dǎo)航菜單代碼
側(cè)滑菜單在網(wǎng)站設(shè)計中應(yīng)用比較廣泛,在許多網(wǎng)站上都可以看到此種類型的菜單。本文給大家介紹jQuery+CSS實(shí)現(xiàn)一個側(cè)滑導(dǎo)航菜單代碼,需要的朋友參考下吧2016-05-05

