Skip to content

Commit

Permalink
feat(): rewrite upload action and add CSRF validation
Browse files Browse the repository at this point in the history
  • Loading branch information
mikejpeters committed Aug 11, 2015
1 parent 9bfa40e commit c691a90
Show file tree
Hide file tree
Showing 3 changed files with 154 additions and 256 deletions.
55 changes: 55 additions & 0 deletions ChunkUploader.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php
namespace boundstate\plupload;


use Yii;
use yii\base\Exception;
use yii\web\UploadedFile;

class ChunkUploader
{
/**
* Processes a chunked file upload.
* @param UploadedFile $uploadedFile
* @param string $path path to write chunks to
* @returns boolean true if file upload is complete, or false if there are more chunks
* @throws Exception
*/
public static function process($uploadedFile, $path) {
if (!$uploadedFile || $uploadedFile->hasError) {
throw new Exception('Failed to upload file');
}

$chunk = (int)Yii::$app->request->getBodyParam('chunk', 0);
$totalChunks = (int)Yii::$app->request->getBodyParam('chunks', 0);

$out = fopen("$path.part", $chunk == 0 ? 'wb' : 'ab');
if (!$out) {
throw new Exception('Failed to open output stream');
}

// Read binary input stream and append it to temporary .part file
$in = fopen($uploadedFile->tempName, 'rb');
if ($in) {
while ($buff = fread($in, 4096)) {
fwrite($out, $buff);
}
} else {
throw new Exception('Failed to open input stream');
}

fclose($in);
fclose($out);

unlink($uploadedFile->tempName);

// Check if all chunks have been processed
if (!$totalChunks || $chunk == $totalChunks - 1) {
// Strip the temp .part suffix off
rename("$path.part", $path);
return true;
}

return false;
}
}
5 changes: 5 additions & 0 deletions Plupload.php
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,11 @@ public function init()
if (!isset($this->errorContainer))
$this->errorContainer = "plupload_{$id}_em";

if (!isset($this->options['multipart_params']))
$this->options['multipart_params'] = [];

$this->options['multipart_params'][Yii::$app->request->csrfParam] = Yii::$app->request->csrfToken;

$bundle = PluploadAsset::register($this->view);

$defaultOptions = [
Expand Down
Loading

0 comments on commit c691a90

Please sign in to comment.