Beispiel #1
0
 /**
  * uploadFile
  *
  * @param  string $mediaDir
  * @param  Request $request
  * @throws HttpException
  *
  * @return string
  */
 public static function uploadFile($mediaDir, Request $request)
 {
     $uploadedFile = null;
     if ($request->files->get('file')) {
         /** @var \Symfony\Component\HttpFoundation\File\UploadedFile $fileFromFileBag */
         $fileFromFileBag = $request->files->get('file');
         $uploadedFile = array('name' => $fileFromFileBag->getClientOriginalName(), 'type' => $fileFromFileBag->getMimeType(), 'tmp_name' => $fileFromFileBag->getPathname(), 'error' => $fileFromFileBag->getError(), 'size' => $fileFromFileBag->getSize());
     }
     $config = new FlowConfig();
     $config->setTempDir($mediaDir);
     $flowRequest = new FlowRequest($request->request->all(), $uploadedFile);
     $flowFile = new FlowFile($config, $flowRequest);
     if ($request->getMethod() === 'GET') {
         if ($flowFile->checkChunk()) {
             header("HTTP/1.1 200 Ok");
         } else {
             header("HTTP/1.1 204 No Content");
             return false;
         }
     } else {
         if ($flowFile->validateChunk()) {
             rename($uploadedFile['tmp_name'], $flowFile->getChunkPath($flowRequest->getCurrentChunkNumber()));
         } else {
             throw new HttpException(400);
         }
     }
     $filename = $mediaDir . '/' . $uploadedFile['name'];
     if ($flowFile->validateFile() && $flowFile->save($filename)) {
         return $filename;
     } else {
         // This is not a final chunk, continue to upload
     }
     return false;
 }
 /**
  * Handle Image Upload
  *
  * @throws \Exception
  *
  * @return ApiFileService
  */
 private function handleImageUpload()
 {
     try {
         $config = new FlowConfig();
         $request = new FlowRequest();
         $basic = new Basic();
         $config->setTempDir(storage_path() . '/tmp');
         $config->setDeleteChunksOnSave(false);
         $totalSize = $request->getTotalSize();
         $uploadFile = $request->getFile();
         $fileName = md5($request->getFileName());
         $extension = explode('.', $request->getFileName())[1];
         $extraNumber = 1;
         if ($totalSize && $totalSize > 1024 * 1024 * 4) {
             throw new \Exception('File size exceeds 4MB', 400);
         }
         while ($this->isNameDuplicated($fileName . '.' . $extension, $this->location)) {
             $fileName = $fileName . $extraNumber;
             ++$extraNumber;
         }
         $fileName = $fileName . '.' . $extension;
         if ($basic->save($this->directory . $this->location . $fileName, $config, $request)) {
             $file = $this->handleImageSave($fileName, $this->location);
             return $file;
         }
         throw new \Exception('unable to save file', 500);
     } catch (\Exception $e) {
         throw new \Exception($e->getMessage(), $e->getCode());
     }
 }
 /**
  */
 public function testFustyRequest_ValidateUpload()
 {
     //// Setup test
     $firstChunk = vfsStream::newFile('temp_file');
     $firstChunk->setContent('1234567890');
     $this->vfs->addChild($firstChunk);
     $fileInfo = new \ArrayObject(array('size' => 10, 'error' => UPLOAD_ERR_OK, 'tmp_name' => $firstChunk->url()));
     $request = new \ArrayObject(array('flowIdentifier' => '13632-prettifyjs', 'flowFilename' => 'prettify.js', 'flowRelativePath' => 'home/prettify.js'));
     $fustyRequest = new FustyRequest($request, $fileInfo);
     $config = new Config();
     $config->setTempDir($this->vfs->url());
     /** @var File $file */
     $file = $this->getMock('Flow\\File', array('_move_uploaded_file'), array($config, $fustyRequest));
     /** @noinspection PhpUndefinedMethodInspection */
     $file->expects($this->once())->method('_move_uploaded_file')->will($this->returnCallback(function ($filename, $destination) {
         return rename($filename, $destination);
     }));
     //// Actual test
     $this->assertTrue($file->validateChunk());
     $this->assertFalse($file->validateFile());
     $this->assertTrue($file->saveChunk());
     $this->assertTrue($file->validateFile());
     $path = $this->vfs->url() . DIRECTORY_SEPARATOR . 'new';
     $this->assertTrue($file->save($path));
     $this->assertEquals(10, filesize($path));
 }
Beispiel #4
0
 /**
  * Handles the file upload
  *
  * @param array $input [description]
  *
  * @return array Variable response - either pending or file uploaded when all chunks
  *               are received.
  */
 public function handle($input = array())
 {
     $validator = Validator::make($input, Model::$rules);
     $user = User::find($input['user_id']);
     if ($validator->fails()) {
         throw new Exception("Validation Issues", 500);
     }
     $filename = time() . $input['flowFilename'];
     $input['original_filename'] = $input['flowFilename'];
     $extension = pathinfo($filename, PATHINFO_EXTENSION);
     $filename = pathinfo($filename, PATHINFO_FILENAME);
     if (!isset($input['path'])) {
         $input['path'] = $user->id . '/';
     }
     $storageLocation = storage_path('user-data/' . $input['path']);
     if (!is_dir($storageLocation)) {
         mkdir($storageLocation, 0755, true);
     }
     $config = new FlowConfig();
     if (!is_dir($storageLocation . 'chunks')) {
         mkdir($storageLocation . 'chunks', 0755, true);
     }
     $config->setTempDir($storageLocation . 'chunks');
     $file = new FlowFile($config);
     if (isset($_POST['ie-app'])) {
         $file->saveChunk();
     } else {
         if ($file->validateChunk()) {
             $file->saveChunk();
         } else {
             // error, invalid chunk upload request, retry
             throw new Exception('Bad request', 400);
         }
     }
     $filename = $this->sanitizeString($filename) . '.' . $extension;
     $localPath = $storageLocation . $filename;
     if ($file->validateFile() && $file->save($localPath)) {
         $input['status'] = 'saved';
         $input['size'] = $input['flowTotalSize'];
         if (isset($_POST['ie-app'])) {
             $input['size'] = filesize($localPath);
         } else {
             $input['size'] = $input['flowTotalSize'];
         }
         $input['path'] = $input['path'] . $filename;
         $input['filename'] = $filename;
         $input['type'] = mime_content_type($localPath);
         $file = Model::create($input);
         //FIXME should use the transformer
         return ['id' => $file->id, 'path' => $file->path, 'links' => $file->links, 'original_filename' => $file->original_filename];
     } else {
         // This is not a final chunk, continue to upload
         return array('pending' => true);
     }
 }
 public function actionUpload()
 {
     /**
      * Removing old chunks
      */
     if (1 == mt_rand(1, 100)) {
         Uploader::pruneChunks($this->temp);
     }
     $response = Yii::$app->response;
     $request = Yii::$app->request;
     $response->format = Response::FORMAT_RAW;
     if ($this->module->allowCrossDomain) {
         $response->headers->add('Access-Control-Allow-Origin', $this->module->allowCORSOrigin);
         $response->headers->add('Access-Control-Allow-Methods', 'GET,HEAD,POST,OPTIONS,TRACE');
         $response->headers->add('Access-Control-Allow-Headers', $this->module->allowCORSHeaders);
     }
     if ($request->isOptions) {
         $response->headers->add('Allow', 'GET,HEAD,POST,OPTIONS,TRACE');
         return;
     }
     $config = new Config();
     $config->setTempDir($this->temp);
     $file = new File($config);
     $filename = $this->getFlowParams()['flowFilename'];
     if (is_callable($this->module->fileNameHandler)) {
         $filename = call_user_func_array($this->module->fileNameHandler, [$filename]);
     }
     if ($request->isGet) {
         if ($file->checkChunk()) {
             $response->statusCode = 200;
         } else {
             $response->statusCode = 204;
             return;
         }
     } else {
         if ($file->validateChunk()) {
             $file->saveChunk();
         } else {
             // error, invalid chunk upload request, retry
             $response->statusCode = 400;
             return;
         }
     }
     if ($file->validateFile() && $file->save($this->target . "/{$filename}")) {
         // File upload was completed
     } else {
         // This is not a final chunk, continue to upload
     }
 }
Beispiel #6
0
 /**
  * @covers ::save
  */
 public function testFile_save_preProcess()
 {
     //// Setup test
     $this->requestArr['flowTotalChunks'] = 1;
     $this->requestArr['flowTotalSize'] = 10;
     $processCalled = false;
     $process = function ($chunk) use(&$processCalled) {
         $processCalled = true;
     };
     $this->config->setPreprocessCallback($process);
     $request = new Request($this->requestArr);
     $file = new File($this->config, $request);
     $chunkPrefix = sha1($request->getIdentifier()) . '_';
     $chunk = vfsStream::newFile($chunkPrefix . '1', 0777);
     $chunk->setContent('1234567890');
     $this->vfs->addChild($chunk);
     $filePath = $this->vfs->url() . DIRECTORY_SEPARATOR . 'file';
     //// Actual test
     $this->assertTrue($file->save($filePath));
     $this->assertTrue(file_exists($filePath));
     $this->assertEquals($request->getTotalSize(), filesize($filePath));
     $this->assertTrue($processCalled);
 }
 public function upload()
 {
     require_once './vendor/autoload.php';
     $request = new Request();
     $staticServerRoot = './Public/ng/app/';
     $chunk = 'statics/chunks_temp_folder';
     $uploaded = 'statics/uploaded';
     $fileNameToSave = md5($request->getIdentifier()) . '.' . pathinfo($request->getFileName())['extension'];
     $pathReturn = $uploaded . '/' . $fileNameToSave;
     $savedFile = $staticServerRoot . $pathReturn;
     $config = new Config();
     $config->setTempDir($staticServerRoot . $chunk);
     $file = new File($config);
     if ($_SERVER['REQUEST_METHOD'] === 'GET') {
         if ($file->checkChunk()) {
             header("HTTP/1.1 200 Ok");
         } else {
             header("HTTP/1.1 204 No Content");
             return;
         }
     } else {
         if ($file->validateChunk()) {
             $file->saveChunk();
         } else {
             // error, invalid chunk upload request, retry
             header("HTTP/1.1 400 Bad Request");
             return;
         }
     }
     if ($file->validateFile() && $file->save($savedFile)) {
         //save to db
         $urlPre = 'http://' . $_SERVER['HTTP_HOST'] . '/';
         $id = M('materials')->add(array('type' => C('MATERIAL_IMAGE'), 'file_name' => $fileNameToSave, 'pic_url' => $urlPre . $pathReturn, 'title' => ''));
         //http://exp/Public/ng/app/statics/uploaded/
         // File upload was completed
         echo json_encode(array('path' => $urlPre . $pathReturn, 'id' => $id));
     } else {
         // This is not a final chunk, continue to upload
         echo 'no';
     }
 }
Beispiel #8
0
 public function testConfig_hashNameCallback()
 {
     $request = new Request($this->requestArr);
     $expHash = sha1($request->getIdentifier());
     $this->assertSame($expHash, Config::hashNameCallback($request));
 }
Beispiel #9
0
 /**
  * @param \MongoGridFS $gridFS storage of the upload (and chunks)
  */
 function __construct(\MongoGridFS $gridFS)
 {
     parent::__construct();
     $this->gridFs = $gridFS;
 }
 public function callbackUpload()
 {
     $config = new Config();
     $config->setTempDir($this->getTempFolder());
     $file = new File($config);
     $request = new Request();
     if ($_SERVER['REQUEST_METHOD'] === 'GET') {
         if ($file->checkChunk()) {
             header("HTTP/1.1 200 Ok");
         } else {
             header("HTTP/1.1 204 No Content");
             exit;
         }
     } else {
         if ($file->validateChunk()) {
             $file->saveChunk();
         } else {
             // error, invalid chunk upload request, retry
             header("HTTP/1.1 400 Bad Request");
             exit;
         }
     }
     if ($file->validateFile() && $file->save($this->getUploadFolder() . '/' . $request->getFileName())) {
         // File upload was completed
         $file = Yii::$app->storage->addFile($this->getUploadFolder() . '/' . $request->getFileName(), $request->getFileName(), 0, true);
         if ($file) {
             @unlink($this->getUploadFolder() . '/' . $request->getFileName());
             $image = Yii::$app->storage->addImage($file->id);
             if ($image) {
                 $image->applyFilter('small-crop');
                 $model = $this->model;
                 $row = $this->getModelItem();
                 if ($row) {
                     $row->flowSaveImage($image);
                     return 'done';
                 }
             }
         }
     } else {
         // This is not a final chunk, continue to upload
     }
 }