PHP,javascript实现大文件上传

HTML代码

<!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();
时间: 2024-07-30 10:08:50

PHP,javascript实现大文件上传的相关文章

JavaScript大文件上传解决方案实例代码

一. 功能性需求与非功能性需求 要求操作便利,一次选择多个文件和文件夹进行上传:支持PC端全平台操作系统,Windows,Linux,Mac 支持文件和文件夹的批量下载,断点续传.刷新页面后继续传输.关闭浏览器后保留进度信息. 支持文件夹批量上传下载,服务器端保留文件夹层级结构,服务器端文件夹层级结构与本地相同. 支持大文件批量上传(20G)和下载,同时需要保证上传期间用户电脑不出现卡死等体验:支持文件夹上传,文件夹中的文件数量达到1万个以上,且包含层级结构. 支持断点续传,关闭浏览器或刷新浏览

django+python大文件上传

大文件上传服务一.前端[webuploader](http://fex.baidu.com/webuploader/ ''webuploader'')二.后端django 2.0.0这里只贴出核心的代码:前端的: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <!--引

基于Nodejs的大文件上传之断点续传

接着<扒一扒Nodejs formidable的onPart>和<也说文件上传之兼容IE789的进度条---丢掉flash>:前面已完成兼容IE789的大文件上传:无flash的低版本进度条,高版本的分段上传,并已为断点续传做好铺垫: 说什么做好铺垫,原本以为Nodejs端已没问题,只剩前端依靠HTML5接着监听abort事件,保存中断时上传到第几块了(断点续传只支持文件比较大,然后意外上传中断了,暂时定50M开启断点续传吧),通过文件内容hash和该文件唯一上传token来记录断

【原创】用JAVA实现大文件上传及显示进度信息

用JAVA实现大文件上传及显示进度信息 ---解析HTTP MultiPart协议 一. 大文件上传基础描述: 各种WEB框架中,对于浏览器上传文件的请求,都有自己的处理对象负责对Http MultiPart协议内容进行解析,并供开发人员调用请求的表单内容. 比如: Spring 框架中使用类似CommonsMultipartFile对象处理表二进制文件信息. 而.NET 中使用HtmlInputFile/ HttpPostedFile对象处理二进制文件信息. 优点:使用框架内置对象可以很方便的

Socket大文件上传

1 public sealed class SocketData 2 { 3 private SocketData() 4 { 5 } 6 7 public static SendFileMode SendFile(Socket socket, string fileName, int maxBufferLength) 8 { 9 SendFileMode flag = SendFileMode.Success; 10 try 11 { 12 using (Stream fs = new Fil

IIS中的大文件上传问题解决方法

IIS出于安全考虑限制了大文件的上传,而网上百度到的大部分解决方法都是用一个管理员权限的记事本打开一个文件修改参数,但是我发现里面根本没有网上所说的那些参数,最后自己找到了修改发布文件的webconfig的方法解决的IIS对大文件上传的限制. 首先在system.web中加入以下代码 [csharp] view plain copy <httpRuntime maxRequestLength="2097151"//最大上传长度 useFullyQualifiedRedirectU

Nodejs+HTML5兼容IE789的大文件上传完整版

业余将大文件上传重新梳理了一遍,后端基于Nodejs:有几个要点感觉很好玩: 兼容性:IE789为代表: 跨域上传:document.domain||middlePage: 多文件上传:input['type=file'] multiple: 拖拽上传:drag drop: 大文件分段:files.slice(s,e): 断点续传:localStorage: 接收分段的文件:formidable.onPart: 陆续写入分段文件:fs.write(fd,bf,offset,length,posi

C# 大文件上传

IHttpModule 分块上传大文件 IHttpModule 分块上传大文件 来源:http://www.cnblogs.com/HeroBeast/archive/2008/03/18/1084874.html 1.一般的在Asp.net里上传文件都是10m左右,要做到大文件上传,必须要改web.config,不过改了web.config有时候也上传不成功,那是每次上传的文件太大,浏览器在这个过程中会超时,采用分块上传的方法就可以避免这种情况. 2.分块上传就是利用post的方法,把数据分块

gitlab使用过程中遇到大文件上传或下载失败的问题,总结一下

环境如下:gitlab服务器redhat,客户端环境mac os,如果是其他环境遇到问题仅供参考 如果gitlab上传代码提示: error: RPC failed; result=22, HTTP code = 411 该问题是由于客户端设置的http_post_buffer大小不足导致的,解决方法如下: 进入到工程所在的终端目录下执行: git config http.postBuffer 524288000 如果gitlab上传代码提示: error: RPC failed; result