使用FormData实现ajax文件异步上传
1.传统的web开发文件上传一般是基于form表单的文件上传,同步的方式,用户体验差,可控性也差
2.异步上传的实现 有以下方式
2.1 借助浏览器插件 一般需要安装一些类似flash的插件 这种方式 缺点:需要安装插件 优点:可控性强,性能高
2.2 这种是伪异步上传,借助表单向隐藏的iframe提交,然后通过iframe通信操作当前页面 这种方式可控行查,体验一般,见下面代码
2.3 借助html5 里的 FormData 对象,可实现进度控制,异步的上传方式,见代码
iframe方式的伪异步上传
up.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.js"></script>
</head>
<body>
<form method="post" action="doup.php" enctype="multipart/form-data" target="up_file">
姓名:<input name="user" type="text"><br>
文件:<input type="file" name="ff"><br>
<input type="submit" value="提交">
</form>
<iframe name="up_file" style="display: none"></iframe>
<div id="res"></div>
</body>
</html>
提交处理程序代码 doup.php
<?php
if($_FILES){
$f=$_FILES['ff'];
$tmp_name=$f['tmp_name'];
if($f['error']===0){
if(is_uploaded_file($tmp_name)){
$file_arr=pathinfo($f['name']);
//防止特殊文件名
if(!is_dir('./upfile')) mkdir('./upfile',0755);
$dst_file='./upfile/'.time()."-".substr(md5($file_arr['filename']),0,5).".".$file_arr['extension'];
$o=move_uploaded_file($tmp_name,$dst_file);
if($o){
$html=<<<E
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.js"></script>
<script>
var parent=window.parent.document;
var img="<img src='$dst_file' style='width:200px;height:200px;'>";
$('#res',parent).html(img);
</script>
E;
echo $html;
}else{
echo 0;
}
}
}
}
后端处理
借助FormData实现真的可控行异步上传
up1.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.js"></script>
</head>
<body>
文件:<input type="file" name="myfile" id="myfile"><br>
<p id="upbtn">
<input type="button" value="异步上传" onclick="upload()">
<span id="uptext" style="display: none">正在上传</span>
<span id="tip"></span>
<button id="stopbtn" style="display: none">停止上传</button>
</p>
<div id="res"></div>
<script>
function upload(){
var fd=new FormData();
var f=$("#myfile")[0].files[0];
if(typeof f !== "object") {
alert('请先选择文件!');
return false;
}
fd.append('myfile',f);
var xhr=new XMLHttpRequest(); xhr.upload.onprogress=function(e){
if(e.lengthComputable){
var percent=Math.round((e.loaded*100/e.total));
console.log('%d',percent);
$('#tip').text(percent);
}
} xhr.onloadstart=function(e){
console.log("load start");
$('#tip').text('开始上传'); $('#stopbtn').one('click',function(){
xhr.abort();
$(this).hide();
});
loading(true); } xhr.onload=function(e){
var res=xhr.responseText;
var res_arr=JSON.parse(res);
console.log(res_arr);
if(res_arr.status==1){
$('#tip').text('上传成功');
$('#res').html(res_arr.dst);
}else{
$('#tip').text(res_arr.info);
} } xhr.onerror=function(){
console.log('error');
$('#tip').text('发生错误');
} xhr.onloadend=function (e){
console.log("load end");
loading(false);
}
xhr.open("POST","./doup1.php",true);
xhr.send(fd);
} function loading(showloading) {
if (showloading) {
$("#uptxt").show();
$("#stopbtn").show();
} else {
$("#uptxt").hide();
$("#stopbtn").hide();
}
} </script>
</body>
</html>
后端处理doup1.php
<?php
$status=0;
$arr=array('status'=>0,'info'=>'没有文件上传或上传配置问题');
if($_FILES){ $f=$_FILES['myfile'];
$tmp_name=$f['tmp_name'];
if($f['error']===0){
if(is_uploaded_file($tmp_name)){
$file_arr=pathinfo($f['name']);
if(!is_dir('./upfile')) mkdir('./upfile',0755);
$dst_file='./upfile/'.time()."-".substr(md5($file_arr['filename']),0,5).".".$file_arr['extension'];
$o=move_uploaded_file($tmp_name,$dst_file);
if($o){
$arr=array('dst'=>$dst_file,'status'=>1);
}else{
$arr=array('status'=>0,'info'=>'移动文件失败');
}
}
}else{
$arr=array('status'=>0,'info'=>"up_err_code:".$f['error']);
}
}
echo json_encode($arr);
使用FormData实现ajax文件异步上传的更多相关文章
- 文件的上传(表单上传和ajax文件异步上传)
项目中用户上传总是少不了的,下面就主要的列举一下表单上传和ajax上传!注意: context.Request.Files不适合对大文件进行操作,下面列举的主要对于小文件上传的处理! 资源下载: 一. ...
- 普通文件的上传(表单上传和ajax文件异步上传)
一.表单上传: html客户端部分: <form action="upload.ashx" method="post" enctype="mul ...
- 文件的上传(1)(表单上传和ajax文件异步上传)
文件的上传(表单上传和ajax文件异步上传) 项目中用户上传总是少不了的,下面就主要的列举一下表单上传和ajax上传!注意: context.Request.Files不适合对大文件进行操作,下面列举 ...
- SpringMVC + AJAX 实现多文件异步上传
转自:https://www.jianshu.com/p/f3987f0f471f 今天,我就这个问题来写一篇如何用 SpringMVC + AJAX 实现的多文件异步上传功能.基本的代码还是沿用上篇 ...
- MVC 5.0(or5.0↓) Ajax.BeginForm 异步上传附件问题,答案是不能的!
MVC 5.0(or5.0↓) Ajax.BeginForm 异步上传附件问题,答案是不能的! (请注意我这里说的异步!) 来看一下下面这段一步提交file的代码 //前台 .cshtml 文件 & ...
- HTML5实现图片文件异步上传
原文:HTML5实现图片文件异步上传 利用HTML5的新特点做文件异步上传非常简单方便,本文主要展示JS部分,html结构.下面的代码并未使用第三发库,如果有参照,请注意一些未展现出来的代码片段.我这 ...
- js 文件异步上传 显示进度条 显示上传速度 预览文件
通常文件异步提交有几个关键 1.支持拖拽放入文件.2.限制文件格式.3.预览图片文件.4.上传进度,速度等,上传途中取消上传.5.数据与文件同时上传 现在开始笔记: 需要一个最基础的元素<inp ...
- MVC文件上传04-使用客户端jQuery-File-Upload插件和服务端Backload组件实现多文件异步上传
本篇使用客户端jQuery-File-Upload插件和服务端Badkload组件实现多文件异步上传.MVC文件上传相关兄弟篇: MVC文件上传01-使用jquery异步上传并客户端验证类型和大小 ...
- 小程序使用 Promise.all 完成文件异步上传
小程序使用 Promise.all 完成文件异步上传 extends [微信小程序开发技巧总结(二) -- 文件的选取.移动.上传和下载 - Kindear - 博客园 (cnblogs.com)] ...
随机推荐
- bootstrap-datepicker 时间范围选择函数封装
bootstrap-datepicker 时间范围选择函数封装 官网 https://bootstrap-datepicker.readthedocs.io/en/latest/index.html ...
- LeetCode第[33]题(Java):Search in Rotated Sorted Array
题目:在翻转有序中搜索 难度:Medium 题目内容: Suppose an array sorted in ascending order is rotated at some pivot unkn ...
- 委托,lambda,匿名方法
lambda表达式其实就是匿名方法的变体或者说简写. 原来我们用 delegate void Del(int x); Del d = delegate(int x) { return x + 1; } ...
- centos 使用yum安装MySQL 5.7
想在centos上安装一个MySQL,使用yum install mysql-server 安装提示仓库没有包,也是醉了. 找了很多博客,发现一个很好用的,推荐给大家. 地址:https://blog ...
- 【sparkStreaming】kafka作为数据源的生产和消费
1.建立生产者发送数据 (1)配置zookeeper属性信息props (2)通过 new KafkaProducer[KeyType,ValueType](props) 建立producer (3) ...
- ARM汇编指令集5
为什么需要多寄存器访问指令? ldr/str每周期只能访问4字节内存,如果需要批量读取.写入内存时太慢,解决方案是stm/ld 举例(uboot start.S 537行) stmia sp, ...
- python基础之递归,声明式编程,面向对象(一)
在函数内部,可以调用其他函数,如果一个函数在内部调用自身本身,这个函数就是递归函数.递归效率低,需要在进入下一次递归时保留当前的状态,解决方法是尾递归,即在函数的最后一步(而非最后一行)调用自己,但是 ...
- LeetCode OJ:Sqrt(x)(平方根)
Implement int sqrt(int x). Compute and return the square root of x. 简单的二分法,注意mid应该选为long,否则容易溢出: cla ...
- vs2013出现错误提示error C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s
这个问题是vs准备弃用strcpy带来的,因为觉得他不太安全 可以尝试在main函数前面加上#pragma warning(disable:4996)即可解决这个问题
- TCPL学习毕节:第六章hash表
对于P126的哈希表构成: struct nlist *install(char *name, char *defn) { struct nlist *np; unsigned hashval; if ...