PHP combined with Web uploader plug-ins to implement fragmented upload file _php skills

Source: Internet
Author: User
Tags flock fread mkdir

Recently studied the next large file upload method, found the Webuploader JS plug-ins to upload large files, you can also refer to this article to learn: "Web uploader File Upload plugin use detailed"

Use

Use Webuploader to divide into simple direct elections to introduce

<!--introduce css-->
<link rel= "stylesheet" type= "Text/css" href= "Webuploader folder/webuploader.css" >

<!--introduce js-->
<script type= "Text/javascript" src= "Webuploader folder/webuploader.js" ></script>

HTML section

<div id= "uploader" class= "wu-example" >
  <!--used to store file information--> <div id=
  "Thelist" Uploader-list "></div>
  <div class=" Btns ">
    <div id=" Picker "> select File </div>
    <button id= "ctlbtn" class= "btn Btn-default" > Start uploading      </button>
  </div>
  </div>

Initializing Web Uploader

JQuery (function () {
    $list = $ (' #thelist '),
      $btn = $ (' #ctlBtn '), state
      = ' pending ',
      uploader;

    Uploader = webuploader.create ({
      //uncompressed image
      Resize:false,
      //swf file path
      swf: ' uploader.swf ',
      // The File receive service side.
      server:upload.php,
      //Select the File button. Optional.
      //Internal according to the current run is created, may be input elements, may also be flash.
      Pick: ' #picker ',
      chunked:true,
      chunksize:2*1024*1024,
      auto:true,
      accept: {
        title: ' Images ',
        extensions: ' gif,jpg,jpeg,bmp,png ',
        mimetypes: ' image/* '
      }
    };

upload.php processing

The following is based on other people's examples of their own to change the PHP background code

Header ("Expires:mon, June June 1997 05:00:00 GMT"); Header ("last-modified:"). Gmdate ("D, D M Y h:i:s").
    "GMT");
    Header ("Cache-control:no-store, No-cache, must-revalidate");
    Header ("Cache-control:post-check=0, pre-check=0", false);

    Header ("Pragma:no-cache"); if ($_server[' request_method '] = = ' OPTIONS ') {exit;//Finish preflight CORS requests here} if (!empty
      request[' Debug ']) {$random = rand (0, intval ($_request[' Debug '));
        if ($random = = 0) {header ("http/1.0 Internal Server Error");
      Exit
    }//Header ("http/1.0 Internal Server Error");
    Exit
    5 minutes Execution Time @set_time_limit (5 * 60);
    Uncomment this one to fake upload time//usleep (5000); Settings//$targetDir = Ini_get ("Upload_tmp_dir"). Directory_separator.
    "Plupload"; $targetDir = ' uploads '.
    Directory_separator. ' File_material_tmp '; $uploadDir = ' uploads '. Directory_separAtor. ' File_material '; $cleanupTargetDir = true; Remove old Files $maxFileAge = 5 * 3600;
    Temp file Age in seconds//Create target dir if (!file_exists ($targetDir)) {@mkdir ($targetDir);
    }//Create target dir if (!file_exists ($uploadDir)) {@mkdir ($uploadDir);
    }//Get a file name if (isset ($_request["name")) {$fileName = $_request["name"];
    } elseif (!empty ($_files)) {$fileName = $_files["File" ["Name"];
    else {$fileName = uniqid ("File_");
    } $oldName = $fileName; $filePath = $targetDir. Directory_separator.
    $fileName; $uploadPath = $uploadDir. Directory_separator.
    $fileName; Chunking might be enabled $chunk = Isset ($_request["chunk"])?
    Intval ($_request["Chunk"]): 0; $chunks = Isset ($_request["chunks"])?
    Intval ($_request["chunks"]): 1;
 Remove Old temp files if ($cleanupTargetDir) {if (!is_dir ($targetDir) | |! $dir = opendir ($targetDir)) {       Die (' {"JSONRPC": "2.0", "error": {"code": +, "message": "Failed to open Temp directory."}, "id": "id"} "); while ($file = Readdir ($dir))!== false) {$tmpfilePath = $targetDir. Directory_separator.
        $file; If temp file is current file proceed to the next if ($tmpfilePath = = "{$filePath}_{$chunk}.part" | | $tmpfilePat
        H = = "{$filePath}_{$chunk}.parttmp") {continue; }//Remove temp file If it is older than the "Max Age" and "isn't" the current file if Preg_match ('/\. part|parttmp) $/', $file) && (@filemtime ($tmpfilePath) < time ()-$maxFileAge)) {@unlink ($tmpfilePath
        );
    } closedir ($dir); }//Open temp file if (! $out = @fopen ("{$filePath}_{$chunk}.parttmp", "WB")) {die (' {jsonrpc ': ' 2.0 ', ' E
    Rror ": {" code ": 102," message ":" Failed to open output stream. "}," id ":" id "} '); } if (!empty ($_files)) {if ($_files["file"] ["Error"] | | !is_uploaded_file ($_files["file"] ["Tmp_name"])) {die (' {"Jsonrpc '):" 2.0 "," error ": {" code ":" The Message ":" Fa
      iled to move uploaded file. "}," id ":" id "} ');  }//Read binary input stream and append it to temp file if (! $in = @fopen ($_files["File" ["Tmp_name"], "RB")
      {die (' {"JSONRPC": "2.0", "error": {"code": "Message": "Failed to open input stream."}, "id": "id"} "); } else {if (! $in = @fopen ("Php://input", "RB")) {die (' {jsonrpc '): ' 2.0 ', ' error ': {' Code ': 10
      1, "message": "Failed to open input stream."}, "id": "id"} ');
    } while ($buff = Fread ($in, 4096)) {fwrite ($out, $buff);
    } @fclose ($out);
    @fclose ($in);
    Rename ("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");
    $index = 0;
    $done = true; for ($index = 0; $index < $chunks; $index + +) {if (!file_exists ("{$filePath}_{$index}.part")) {$done
        = false;
      Break



}
    }    if ($done) {$pathInfo = PathInfo ($fileName);
      $HASHSTR = substr (MD5 ($pathInfo [' basename ']), 8,16); $hashName = Time (). $hashStr.
      '. ' $pathInfo [' extension ']; $uploadPath = $uploadDir.

      Directory_separator. $hashName; if (! $out = @fopen ($uploadPath, WB)) {die (' {jsonrpc '): "2.0", "error": {"code": 102, "message": "Failed to OP
      En output stream. "}," id ":" id "} '); } if (Flock ($out, lock_ex)) {for ($index = 0; $index < $chunks; $index + +) {if (! $in = @fop
          En ("{$filePath}_{$index}.part", "RB")) {break;
          while ($buff = Fread ($in, 4096)) {fwrite ($out, $buff);
          } @fclose ($in);
        @unlink ("{$filePath}_{$index}.part");
      Flock ($out, lock_un);
      } @fclose ($out); $response = [' Success ' =>true, ' oldname ' => $oldName, ' filepaht ' => $uploadPath, ' fil
 Esize ' => $data [' Size '],       ' Filesuffixes ' => $pathInfo [' extension '], ' file_id ' => $data [' id '],];
    Die (Json_encode ($response));
 }//Return Success JSON-RPC response Die (' {jsonrpc ': ' 2.0 ', ' result ': null, ' ID ': ' ID '} ');

The above is the entire content of this article, I hope to help you learn.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.