formdata方式上传文件,支持大文件分割上传
1、upload.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<html>
<head>
<title></title> </head> <body>
<form enctype="multipart/form-data" id="uploadImg">
上传文件:
<input name="file" type="file" id="file">
</form>
</body>
</html>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
$(function(){
$('input[type="file"]').on('change', function(){
var file = this.files[0];
var formData = new FormData($('#uploadImg')[0]);
formData.append('file', file);
console.log(formData.get('file'))
$.ajax({
url: 'upload.php',
type: 'POST',
cache: false,
data: formData,
//dataType: 'json',
//async: false,
processData: false, //不需要对数据做任何预处理
contentType: false, //不设置数据格式
}).done(function(res) {
console.log(res)
}).fail(function(res) {
console.log(res)
});
});
})
</script>
2、upload.php
<?php
header("Content-type:text/html;charset=utf-8");
//print_r($_FILES);
$uptypes=array(
'image/jpg',
'image/jpeg',
'image/png',
'image/pjpeg',
'image/gif',
'image/bmp',
'image/x-png'
); $max_file_size=200000000; //上传文件大小限制, 单位BYTE $file=$_FILES["file"];
$fileName=$file["name"];
$filetype = $file["type"];
$filesize = $file["size"]; if(!in_array($filetype, $uptypes)){ // 文件类型判断
echo "文件类型不符!";
exit;
}
if($filesize > $max_file_size){ // 文件大小判断
echo "文件太大!";
exit;
}
if (!is_dir("image/")) { //创建路径
mkdir("image/");
}
$url = "image/";
//当文件存在
if (file_exists($url.$fileName)) {
//echo $fileName." already exists.";
echo $url.$fileName;
}else{//当文件不存在
$url=$url.$fileName;
move_uploaded_file($_FILES["file"]["tmp_name"],$url);
echo $url;
}
?>
大文件分割上传
JS思路
1.监听上传按钮的onchange事件
2.获取文件的FILE对象
3.把文件的FILE对象进行切割,并且附加到FORMDATA对象中
4.把FORMDATA对象通过AJAX发送到服务器
5.重复3、4步骤,直到文件发送完。
PHP思路
1.建立上传文件夹
2.把文件从上传临时目录移动到上传文件夹
3.所有的文件块上传完成后,进行文件合成
4.删除文件夹
5.返回上传后的文件路径
DEMO代码
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#progress{
width: 300px;
height: 20px;
background-color:#f7f7f7;
box-shadow:inset 0 1px 2px rgba(0,0,0,0.1);
border-radius:4px;
background-image:linear-gradient(to bottom,#f5f5f5,#f9f9f9);
} #finish{
background-color: #149bdf;
background-image:linear-gradient(45deg,rgba(255,255,255,0.15) 25%,transparent 25%,transparent 50%,rgba(255,255,255,0.15) 50%,rgba(255,255,255,0.15) 75%,transparent 75%,transparent);
background-size:40px 40px;
height: 100%;
}
form{
margin-top: 50px;
}
</style>
</head>
<body>
<div id="progress">
<div id="finish" style="width: 0%;" progress="0"></div>
</div>
<form action="./upload.php">
<input type="file" name="file" id="file">
<input type="button" value="停止" id="stop">
</form>
<script>
var fileForm = document.getElementById("file");
var stopBtn = document.getElementById('stop');
var upload = new Upload(); fileForm.onchange = function(){
upload.addFileAndSend(this);
} stopBtn.onclick = function(){
this.value = "停止中";
upload.stop();
this.value = "已停止";
} function Upload(){
var xhr = new XMLHttpRequest();
var form_data = new FormData();
const LENGTH = 1024 * 1024;
var start = 0;
var end = start + LENGTH;
var blob;
var blob_num = 1;
var is_stop = 0
//对外方法,传入文件对象
this.addFileAndSend = function(that){
var file = that.files[0];
blob = cutFile(file);
sendFile(blob,file);
blob_num += 1;
}
//停止文件上传
this.stop = function(){
xhr.abort();
is_stop = 1;
}
//切割文件
function cutFile(file){
var file_blob = file.slice(start,end);
start = end;
end = start + LENGTH;
return file_blob;
};
//发送文件
function sendFile(blob,file){
var total_blob_num = Math.ceil(file.size / LENGTH);
form_data.append('file',blob);
form_data.append('blob_num',blob_num);
form_data.append('total_blob_num',total_blob_num);
form_data.append('file_name',file.name); xhr.open('POST','./upload.php',false);
xhr.onreadystatechange = function () {
var progress;
var progressObj = document.getElementById('finish');
if(total_blob_num == 1){
progress = '100%';
}else{
progress = Math.min(100,(blob_num/total_blob_num)* 100 ) +'%';
}
progressObj.style.width = progress;
var t = setTimeout(function(){
if(start < file.size && is_stop === 0){
blob = cutFile(file);
sendFile(blob,file);
blob_num += 1;
}else{
setTimeout(t);
}
},1000);
}
xhr.send(form_data);
}
} </script>
</body>
</html>
php代码部分
<?php
class Upload{
private $filepath = './upload'; //上传目录
private $tmpPath; //PHP文件临时目录
private $blobNum; //第几个文件块
private $totalBlobNum; //文件块总数
private $fileName; //文件名 public function __construct($tmpPath,$blobNum,$totalBlobNum,$fileName){
$this->tmpPath = $tmpPath;
$this->blobNum = $blobNum;
$this->totalBlobNum = $totalBlobNum;
$this->fileName = $fileName; $this->moveFile();
$this->fileMerge();
} //判断是否是最后一块,如果是则进行文件合成并且删除文件块
private function fileMerge(){
if($this->blobNum == $this->totalBlobNum){
$blob = '';
for($i=1; $i<= $this->totalBlobNum; $i++){
$blob .= file_get_contents($this->filepath.'/'. $this->fileName.'__'.$i);
}
file_put_contents($this->filepath.'/'. $this->fileName,$blob);
$this->deleteFileBlob();
}
} //删除文件块
private function deleteFileBlob(){
for($i=1; $i<= $this->totalBlobNum; $i++){
@unlink($this->filepath.'/'. $this->fileName.'__'.$i);
}
} //移动文件
private function moveFile(){
$this->touchDir();
$filename = $this->filepath.'/'. $this->fileName.'__'.$this->blobNum;
move_uploaded_file($this->tmpPath,$filename);
} //API返回数据
public function apiReturn(){
if($this->blobNum == $this->totalBlobNum){
if(file_exists($this->filepath.'/'. $this->fileName)){
$data['code'] = 2;
$data['msg'] = 'success';
$data['file_path'] = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['DOCUMENT_URI']).str_replace('.','',$this->filepath).'/'. $this->fileName;
}
}else{
if(file_exists($this->filepath.'/'. $this->fileName.'__'.$this->blobNum)){
$data['code'] = 1;
$data['msg'] = 'waiting for all';
$data['file_path'] = '';
}
}
header('Content-type: application/json');
echo json_encode($data);
} //建立上传文件夹
private function touchDir(){
if(!file_exists($this->filepath)){
return mkdir($this->filepath);
}
}
} //实例化并获取系统变量传参
$upload = new Upload($_FILES['file']['tmp_name'],$_POST['blob_num'],$_POST['total_blob_num'],$_POST['file_name']);
//调用方法,返回结果
$upload->apiReturn();
formdata方式上传文件,支持大文件分割上传的更多相关文章
- HTML上传文件支持大文件上传,下载
上传 1.修改配置文件web.config,在<system.webServer>下面加入 <security> <requestFiltering > <r ...
- 居于H5的多文件、大文件、多线程上传解决方案
文件上传在web应用中是比较常见的功能,前段时间做了一个多文件.大文件.多线程文件上传的功能,使用效果还不错,总结分享下. 一. 功能性需求与非功能性需求 要求操作便利,一次选择多个文件进行上传: 支 ...
- HTTP文件上传服务器-支持超大文件HTTP断点续传的实现办法
最近由于笔者所在的研发集团产品需要,需要支持高性能的大文件http上传,并且要求支持http断点续传.笔者在以前的博客如何实现支持大文件的高性能HTTP文件上传服务器已经介绍了实现大文件上传的一些基本 ...
- 基于bootstrap的上传插件fileinput实现ajax异步上传功能(支持多文件上传预览拖拽)
首先需要导入一些js和css文件 ? 1 2 3 4 5 6 <link href="__PUBLIC__/CSS/bootstrap.css" rel="exte ...
- C++中使用内存映射文件处理大文件
引言 文件操作是应用程序最为基本的功能之一,Win32 API和MFC均提供有支持文件处理的函数和类,常用的有Win32 API的CreateFile().WriteFile().ReadFile() ...
- .net上传文件,大文件及下载方式汇总(转)
原文地址:http://www.360doc.com/content/19/1219/10/67993814_880731215.shtml Brettle.Web.NeatUpload.dll 文件 ...
- 前端上传视频、图片、文件等大文件 组件Plupload使用指南
demo:https://blog.csdn.net/qq_30100043/article/details/78491993 Plupload上传插件中文帮助文档网址:http://www.phpi ...
- 聊一聊jquery文件上传(支持多文件上传)
谈到文件上传,现在一般都用现成的组件可以使用.PC端的可以使用uploadify.针对微网站H5也有uploadifive.但是这组件并不能满足各种场景的需求,例如:预览 切图 放大缩小,取消之类的. ...
- 精讲RestTemplate第6篇-文件上传下载与大文件流式下载
本文是精讲RestTemplate第6篇,前篇的blog访问地址如下: 精讲RestTemplate第1篇-在Spring或非Spring环境下如何使用 精讲RestTemplate第2篇-多种底层H ...
随机推荐
- LAMP框架
一基本常识 LNMP (Linux + Nginx + MySQL + PHP) LAMP (Linux + Apache + MySQL + PHP) //php作为Apache的模块Apache. ...
- 【Linux开发】Linux V4L2驱动架构解析与开发导引
Linux V4L2驱动架构解析与开发导引 Andrew按:众所周知,linux中可以采用灵活的多层次的驱动架构来对接口进行统一与抽象,最低层次的驱动总是直接面向硬件的,而最高层次的驱动在linux中 ...
- 无法在发送 HTTP 标头之后进行重定向
public ActionResult Index2() { Response.Buffer = true; Response.Clear(); return Redirect("/Wech ...
- GeoAdapter实现WMS、WMTS、ArcGIS MapService的区域权限授权管理
背景: 在实际GIS应用中,我们经常会发布GIS地图服务,然后供WebGIS调用.在某些特殊情况下,需要对服务进行区域授权,特定的用户只能够浏览特定范围内的地图数据.通常情况下大家采用的实现方式是使用 ...
- 基于BufferedImage的图像滤镜演示
package chapter2; import javax.imageio.ImageIO;import javax.swing.*;import javax.swing.filechooser.F ...
- wordpress添加index页面跳转链接
1. 制作page页面 1.1 在themes下的主题目录新建一个page页面 1.2 在wordpress后台新建页面跟在目录页面中相同名字的页面文件 1.3 复制后台页面中的古定链接 1.4 在i ...
- 【 React -- 2/100 】使用React实现评论功能
React| 组件化 | 递归 | 生成唯一ID 需要探究一下 .find() 和 findIndex() 的区别 import React from 'react' import './commen ...
- Educational Codeforces Round 68 (Rated for Div. 2) C. From S To T (字符串处理)
C. From S To T time limit per test1 second memory limit per test256 megabytes inputstandard input ou ...
- Educational Codeforces Round 55 (Rated for Div. 2) B. Vova and Trophies (贪心+字符串)
B. Vova and Trophies time limit per test2 seconds memory limit per test256 megabytes inputstandard i ...
- SpringBoot之集成数据库
一.集成 MySQL 数据库 1.1 配置 MySQL 添加依赖 <dependencies> <!--Spring 数据库相关依赖--> <dependency> ...