public static function add($formname, $newpath, $newname = '') { $storage = new \Upload\Storage\FileSystem($newpath); $file = new \Upload\File($formname, $storage); // Optionally you can rename the file on upload if ($newname) { $file->setName($newname); } // Validate file upload // MimeType List => http://www.webmaster-toolkit.com/mime-types.shtml $file->addValidations(array(new \Upload\Validation\Mimetype(array('image/png', 'image/gif', 'image/jpeg', 'image/jpeg')), new \Upload\Validation\Size('5M'))); // Try to upload file $errors = ''; try { // Success! $file->upload(); } catch (\Exception $e) { // Fail! $errors = $file->getErrors(); } if ($errors) { return $errors; } else { // Access data about the file that has been uploaded return array('name' => $file->getNameWithExtension(), 'extension' => $file->getExtension(), 'mime' => $file->getMimetype(), 'size' => $file->getSize()); } }
/** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $storage = new \Upload\Storage\FileSystem('../resources/assets/images'); $file = new \Upload\File('image', $storage); $new_filename = uniqid(); $file->setName($new_filename); $file->addValidations(array(new \Upload\Validation\Mimetype('image/jpeg'), new \Upload\Validation\Size('5M'))); $data = array('name' => $file->getNameWithExtension(), 'extension' => $file->getExtension(), 'mime' => $file->getMimetype(), 'size' => $file->getSize(), 'md5' => $file->getMd5(), 'dimensions' => $file->getDimensions()); $file->upload(); $book = new Book($request->all()); $book->category_id = $request->all()['categoryId']; $book->unit_id = $request->all()['unitId']; $book->source_id = $request->all()['sourceId']; $book->image = $data['name']; $user = User::find(Auth::id()); $user->books()->save($book); return redirect(route('admin.books.show', $book->id)); }
public static function cambiarImagen($carpeta, $id, $tamanos) { if (\Slim\Slim::getInstance()->getMode() != 'testing') { $dir = __DIR__ . '/../public/img/' . $carpeta . '/' . $id; if (!is_dir($dir)) { mkdir($dir, 0777, true); } $storage = new \Upload\Storage\FileSystem($dir, true); $file = new \Upload\File('imagen', $storage); $filename = 'original'; $file->setName($filename); $file->addValidations(array(new \Upload\Validation\Mimetype(array('image/png', 'image/jpg', 'image/jpeg', 'image/gif')), new \Upload\Validation\Size('1M'))); $file->upload(); foreach ($tamanos as $res) { $image = new ZebraImage(); $image->source_path = $dir . '/' . $file->getNameWithExtension(); $image->target_path = $dir . '/' . $res . '.png'; $image->preserve_aspect_ratio = true; $image->enlarge_smaller_images = true; $image->preserve_time = true; $image->resize($res, $res, ZEBRA_IMAGE_CROP_CENTER); } } }
public function uploadAction() { $storage = new \Upload\Storage\FileSystem('uploads'); $file = new \Upload\File('file', $storage); $new_filename = uniqid(); $file->setName($new_filename); $_SESSION['uploads'][] = $new_filename . '.' . $file->getExtension(); $file->addValidations(array(new \Upload\Validation\Mimetype(array('image/png', 'image/gif', 'image/jpg')), new \Upload\Validation\Size('6M'))); $errors = array(); try { $file->upload(); } catch (Exception $e) { $errors = $file->getErrors(); } $response_data = array('errors' => $errors); echo json_encode($response_data); }
<?php require '../vendor/autoload.php'; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\ResponseInterface; $app = new \Slim\Slim(array("debug" => true, 'templates.path' => '../templates')); // Define app routes $app->get('/home', function () use($app) { $app->render('home.php', array()); }); $app->post('/shrink', function () use($app) { $storage = new \Upload\Storage\FileSystem("/tmp"); $file = new \Upload\File("file", $storage); $newFilename = uniqid(); $file->setName($newFilename); // Validate file upload // Ensure file is of type "image/png" $file->addValidations(array(new \Upload\Validation\Mimetype('image/png'))); // Try to upload file try { // Success! $file->upload(); } catch (\Exception $e) { // Fail! $errors = $file->getErrors(); die; } $compressed_png_content = shell_exec("pngquant - < " . escapeshellarg("/tmp/{$newFilename}")); header('Content-Type:image/png'); echo $compressed_png_content; });
public function TestUploadIt() { $req = App::request(); if ($req->isPost()) { echo ROOT; $storage = new \Upload\Storage\FileSystem(ROOT . "/data/v"); $file = new \Upload\File('gfile', $storage); // Optionally you can rename the file on upload $new_filename = uniqid(); $file->setName($new_filename); // Validate file upload // MimeType List => http://www.webmaster-toolkit.com/mime-types.shtml $file->addValidations(array(new \Upload\Validation\Mimetype('video/mp4'), new \Upload\Validation\Size('750M'))); // Access data about the file that has been uploaded $data = array('name' => $file->getNameWithExtension(), 'extension' => $file->getExtension(), 'mime' => $file->getMimetype(), 'size' => $file->getSize(), 'md5' => $file->getMd5(), 'dimensions' => $file->getDimensions()); // Try to upload file try { // Success! $file->upload(); } catch (\Exception $e) { // Fail! $errors = $file->getErrors(); var_dump($errors); } echo "just for post"; } else { App::render('/viewku/formupload'); } }
* { * "succes": "fichier upload" * } * * @apiErrorExample Error-Response: * HTTP/1.1 404 Not Found * { * "error": code error * } */ $app->post('/banniere/', function ($request, $response) use($app) { try { $yaml = new Parser(); $config = $yaml->parse(file_get_contents('config/config.yml')); $storage = new \Upload\Storage\FileSystem($config['parameters']["dir_files"] . 'mobile'); $file = new \Upload\File('file', $storage); //on passe son id en nom $file->setName('banniere_mobile'); $file->addValidations(array(new \Upload\Validation\Mimetype(array('image/png', 'image/jpeg', 'image/pjpeg')), new \Upload\Validation\Size('5M'))); //check la validité du fichier pour supprimer le/les ancienne(s) image(s) if ($file->validate()) { foreach (glob($config['parameters']["dir_files"] . 'mobile/banniere_mobile.*') as $oldFile) { unlink($oldFile); } } //on upload le fichier $file->upload(); $response = $response->withJson(array("status" => array("succes" => "fichier upload")), 200); } catch (\Exception $e) { if (!empty($file)) { $response = $response->withJson(array("status" => array("error" => $file->getErrors())), 400);
$app->post('/write', $registered(), function () use($app) { // Add custom functions! require_once 'app/functions/slugify.php'; $req = $app->req; $user_id = $_SESSION[$app->config->get('auth.session')]; $post = new Post(); $post->title = $req->title; $post->content = $req->content; $post->content_text = $req->content_text; $post->author = $user_id; $post->slug = slugify($req->title); $post->status = 'published'; if (isset($_FILES['file'])) { // Upload photo first $storage = new \Upload\Storage\FileSystem($_SERVER['DOCUMENT_ROOT'] . '/user-uploads/' . $user_id); $file = new \Upload\File('file', $storage); // Optionally you can rename the file on upload $new_filename = uniqid(); $file->setName($new_filename); // Validate file upload // MimeType List => http://www.iana.org/assignments/media-types/media-types.xhtml $file->addValidations(array(new \Upload\Validation\Mimetype(['image/png', 'image/jpg', 'image/jpeg', 'image/gif', 'image/svg']), new \Upload\Validation\Size('2M'))); // Access data about the file that has been uploaded $data = array('name' => $file->getNameWithExtension()); $post->post_image = $data['name']; // Try to upload file try { // Success! $file->upload(); $post->save(); } catch (\Exception $e) {
require __DIR__ . '/../src/mysql.php'; // Routes $locations = entity('locations'); $meseros = entity('meseros'); $encuestas = entity('encuestas'); $app->get('/api/locations', $locations["findAll"]); $app->get('/api/locations/[{id}]', $locations["findById"]); $app->post('/api/locations', $locations["insert"]); $app->get('/api/meseros', $meseros["findAll"]); $app->post('/api/meseros', $meseros["insert"]); $app->post('/api/put/meseros', $meseros["update"]); $app->get('/api/meseros/[{id}]', $meseros["findById"]); $app->post('/api/delete/meseros/[{id}]', $meseros["delete"]); $app->post('/api/picture', function ($request, $response, $args) { $storage = new \Upload\Storage\FileSystem('/Users/foxtrot/Documents/code/other/encuesta/public/meseros', true); $file = new \Upload\File('picture', $storage); $new_filename = $request->getParsedBody()['id']; $file->setName($new_filename); $file->setExtension("jpg"); try { // Success! $file->upload(); } catch (\Exception $e) { // Fail! $errors = $file->getErrors(); error_log("Errors: " . print_r($errors, TRUE)); } return $response->withRedirect('/'); }); $app->get('/api/encuestas', $encuestas["findAll"]); $app->post('/api/encuestas', $encuestas["insert"]);
try { // Success! $file->upload(); header("Content-Type: text/html"); print json_encode(array("status" => "success", "filename" => $file->getName() . '.' . $file->getExtension())); exit; } catch (\Exception $e) { header("Content-Type: text/html"); print json_encode(array("status" => "error", "errors" => $file->getErrors())); exit; } }); $app->post('/upload/file', function () use($app) { // Setup file storage $file_storage = new \Upload\Storage\FileSystem("../assets/files"); $file = new Upload\File("file", $file_storage); $file->addValidations(array(new Upload\Validation\Mimetype(array('application/pdf')))); $file->setName(uniqid()); try { // Success! $file->upload(); header("Content-Type: text/html"); print json_encode(array("status" => "success", "filename" => $file->getName() . '.' . $file->getExtension())); exit; } catch (\Exception $e) { header("Content-Type: text/html"); print json_encode(array("status" => "error", "errors" => $file->getErrors())); exit; } }); $app->get("/mailsubscription/:uid", function ($uid) {
/** * @return void */ private function pluginImage() { if (empty($this->controller->action)) { return; } $publicPath = __DIR__ . '/../../public'; $imageDomain = trim($this->config->get('admin', 'imageDomain'), '/'); $imagePath = trim($this->config->get('admin', 'imagePath'), '/'); if (!empty($_FILES)) { if (isset($_FILES['image']['error']) && $_FILES['image']['error'] === 0) { if (!is_dir($publicPath . '/' . $imagePath . '/' . $this->controller->table)) { mkdir($publicPath . '/' . $imagePath . '/' . $this->controller->table); } $storage = new \Upload\Storage\FileSystem($publicPath . '/' . $imagePath . '/' . $this->controller->table, true); $file = new \Upload\File('image', $storage); $file->addValidations([new \Upload\Validation\Mimetype(['image/png', 'image/jpg', 'image/jpeg', 'image/gif', 'image/tif']), new \Upload\Validation\Size('5M')]); $file->upload(); } return; } $structure = []; $directory = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($publicPath . '/' . $imagePath, \RecursiveDirectoryIterator::SKIP_DOTS)); foreach ($directory as $file) { if ('.' === substr($file->getFilename(), 0, 1)) { continue; } $pathname = $file->getPathname(); $dir = basename($file->getPath()); //structure by modification time and filename $structure[$dir][$file->getMtime() . $file->getFilename()] = str_replace($publicPath, '', $pathname); krsort($structure[$dir]); } $content = $this->factory->template()->file(__DIR__ . '/../Views/Admin/Plugins/Image')->set('structure', $structure)->set('data', $this->data)->set('imageDomain', $imageDomain)->set('imagePath', $imagePath)->set('table', $this->controller->table)->set('action', $this->controller->action)->set('id', $this->controller->id); foreach ($this->data[$this->controller->table]['columns'] as $columnName => $column) { if (isset($column['type']) && $column['type'] == 'image') { $this->data[$this->controller->table]['plugins'][$columnName] = $content->set('column', $columnName)->render(); } } return; }
protected function uploadFile($field_name) { $storage = new \Upload\Storage\FileSystem(PUBLIC_DIR_UPLOAD); $file = new \Upload\File($field_name, $storage); $file->setName(uniqid()); $file->addValidations(array(new \Upload\Validation\Mimetype(['image/png', 'image/jpeg']), new \Upload\Validation\Size('2M'))); try { $data = array('status' => true, 'name' => $file->getNameWithExtension(), 'extension' => $file->getExtension(), 'mime' => $file->getMimetype(), 'size' => $file->getSize(), 'md5' => $file->getMd5(), 'dimensions' => $file->getDimensions()); $file->upload(); } catch (\Exception $e) { $data = ['status' => false, 'message' => $file->getErrors(), 'name' => ""]; } return $data; }
public function uploadMedia(Request $request, Response $response, $arguments) { $errors = []; foreach ($_FILES as $key => $file) { $storage = new \Upload\Storage\FileSystem('uploads'); $file = new \Upload\File($key, $storage); try { $file->setName(s($file->getName())->slugify()); $file->upload(); } catch (\Exception $e) { array_push($errors, 'Failed to upload ' . $file->getNameWithExtension()); } } return $response->withJson(['errors' => $errors], 200, JSON_PRETTY_PRINT); }
<?php use Upload\Storage; $app->get('/upload', function () use($app) { $app->render('test/upload.php'); })->name('test.upload'); $app->post('/upload', function () use($app) { $storage = new \Upload\Storage\FileSystem(INC_ROOT . '/images/user/icon'); $file = new \Upload\File('prof_pic', $storage); // Optionally you can rename the file on upload // Setting a randomly generated name - could be userful if it is stored in the database // $new_filename = uniqid(); // check if the user already has an image, $file->setName($app->auth->username); // Validate file upload // MimeType List => http://www.iana.org/assignments/media-types/media-types.xhtml $file->addValidations(array(new \Upload\Validation\Mimetype(array('image/png', 'image/jpg', 'image/jpeg')), new \Upload\Validation\Size('500K'))); // Access data about the file that has been uploaded $data = array('name' => $file->getNameWithExtension(), 'extension' => $file->getExtension(), 'mime' => $file->getMimetype(), 'size' => $file->getSize()); // Try to upload file try { // Success! $file->upload(); } catch (\Exception $e) { // Fail! $errors = $file->getErrors(); $app->flash('global', 'Rip that image'); return $app->render('test/upload.php', ['errors' => $errors]); } $app->flash('global', 'Upload was successful'); return $app->response->redirect($app->urlFor('home'));
public function upload_csv() { $storage = new \Upload\Storage\FileSystem($this->Service->Config()->get_basepath() . '/static/uploads'); $file = new \Upload\File('file', $storage); // Optionally you can rename the file on upload $new_filename = uniqid(); $file->setName($new_filename); // Validate file upload // MimeType List => http://www.webmaster-toolkit.com/mime-types.shtml $file->addValidations(array(new \Upload\Validation\Mimetype(array('text/csv', 'text/plain')), new \Upload\Validation\Size('5M'))); // Access data about the file that has been uploaded $data = array('name' => $file->getNameWithExtension(), 'extension' => $file->getExtension(), 'mime' => $file->getMimetype(), 'size' => $file->getSize(), 'md5' => $file->getMd5(), 'dimensions' => $file->getDimensions()); // var_dump($data); // Try to upload file try { // Success! if ($file->upload()) { return $data; } } catch (\Exception $e) { // Fail! $errors = $file->getErrors(); var_dump($errors); } }
$app['http']->response->setBody($app['encoder']->encode($body)); $app['http']->stop(); } } // 检查是否存在上传文件。 if (empty($_FILES[$files_key]['tmp_name'])) { $body['code'] = 30109; $body['message'] = '没有文件上传。'; $headers['setCommonHeader'](); $app['http']->response->setStatus(200); $app['http']->response->setBody($app['encoder']->encode($body)); $app['http']->stop(); } /* 创建上传组件相关对象 */ $storage = new \Upload\Storage\FileSystem($files_uploads, true); $file = new \Upload\File($files_key, $storage); $data = array(); $i = 0; $k = 0; /* 文件上传数量限制 */ if ($file->count() > 5) { $error = '已到最大数量了!'; $body['code'] = 30109; $body['message'] = $error; $headers['setCommonHeader'](); $app['http']->response->setStatus(200); $app['http']->response->setBody($app['encoder']->encode($body)); $app['http']->stop(); } $file->addValidations(array(new \Upload\Validation\Mimetype(array('image/png', 'image/jpeg')), new \Upload\Validation\Size('5M')))->beforeValidate(function ($fileInfo) use($file) { /* 文件上传失败,捕获错误代码 */
public function upload() { $this->logger->info("======================"); $this->logger->info("upload() Method called"); $file = new \Upload\File($this->getFileName(), $this->source); $file->addValidations($this->getValidations()); $this->logger->info("Discovered file :" . $file->getNameWithExtension() . " tmpName:" . $file->getRealPath()); try { $tmpName = $file->getRealPath(); $originalName = $file->getNameWithExtension(); $hash = md5_file($tmpName); $this->logger->info("Created hash for file:" . $hash); $this->logger->info("Checking if file with hash = {$hash} exists in db."); $fileExistsInDb = $this->fileExistsInDb($hash); if ($fileExistsInDb !== false) { $this->logger->info("Found " . json_encode($fileExistsInDb)); $this->logger->info("File already exists"); return $this->setResult(["success" => false, "message" => "Same File", "id" => abs($fileExistsInDb["id"]), "error" => 4]); } $this->logger->info("File is unique, file will be validated before saving to db."); if (!$file->validate()) { $this->logger->info("File is invalid. " . json_encode($file->getErrors())); return $this->setResult(["success" => false, "id" => -1, "message" => "Invalid file type.\nMimeType: " . $file->getMimeType(), "additionalInfo" => implode($file->getErrors()), "error" => 3]); } $this->logger->info("File passed validation. Saving to db."); $stmnt = $this->db->prepare("Insert into upload (hash) values (:hash) returning id"); $stmnt->bindParam(':hash', $hash); $stmnt->execute(); $saveResult = $stmnt->fetch()['id']; $this->logger->info("Successfully saved to db with id {$saveResult}"); if (!$saveResult) { $this->logger->info("Failure to save file to db."); return $this->setResult(["success" => false, "id" => -1, "message" => "Error in data.", "error" => 7]); } $uploadBaseDir = $this->container["uploadConfig"]["path"]; $adapter = new Local($uploadBaseDir, 0); $fileParentDir = (string) round($saveResult, -4); if (!$adapter->has($fileParentDir)) { $config = new Config(['visibility' => 'public']); $adapter->createDir($fileParentDir, $config); } $file = new \Upload\File($this->getFileName(), new FileSystem($uploadBaseDir . $fileParentDir)); $file->addValidations($this->getValidations()); $file->setName($saveResult); $newFullPath = $uploadBaseDir . $fileParentDir . DS . $file->getNameWithExtension(); $extension = $file->getExtension(); $this->logger->info("File will be uploaded to {$newFullPath}"); $result = $file->upload(); if (!$result) { return $this->setResult(["success" => false, "id" => -1, "message" => "Error uploading file.", "error" => 8]); } $this->logger->info("File upload successful."); $cvlizerConfig = $this->container["cvlizer"]; $this->logger->info("Reading data of \n {$newFullPath}"); $fileContents = file_get_contents($newFullPath); $soapClient = new \SoapClient($cvlizerConfig["uri"]); $this->logger->info("Parsing data with arguments : extractToXML(" . $cvlizerConfig["username"] . "," . $cvlizerConfig["password"] . ", EN, " . $cvlizerConfig["model"] . ", ..., " . $extension . ")"); $parsedData = $soapClient->extractToXML($cvlizerConfig["username"], $cvlizerConfig["password"], "EN", $cvlizerConfig["model"], $fileContents, $extension); if (is_soap_fault($parsedData)) { $message = "Error parsing file.\n" . $parsedData->faultcode . "\n" . $parsedData->faultstring; $this->logger->info($message); return $this->setResult(["success" => false, "id" => -1, "message" => $message, "error" => 9]); } $this->logger->info("Parse successful."); $xmlFile = fopen($cvlizerConfig["xmlSavePath"] . abs($saveResult) . ".xml", "w") or die("Unable to open file!"); $this->logger->info("Writing to file. {$xmlFile}"); fwrite($xmlFile, $parsedData); fclose($xmlFile); $this->logger->info("Write successful."); $updateStatement = $this->db->update(["name" => $originalName, "ftype" => $extension, "created" => date("Y-m-d H:i:s")])->table("upload")->where("id", "=", $saveResult); $affectedRows = $updateStatement->execute(); $this->logger->info("Executing sql:\n" . $updateStatement->__toString()); if ($affectedRows) { $this->logger->info("Successfully executed"); $cv = new CV($parsedData); $cv->setId($saveResult); $saved = $cv->saveToDb(); $this->logger->info(json_encode($saved)); if ($saved) { $this->setResult(["success" => true, "id" => $saveResult, "message" => "New", "error" => 0]); } } else { $message = "Error saving data."; $this->logger->info($message); return $this->setResult(["success" => false, "id" => 10, "message" => $message]); } } catch (\Exception $e) { $this->logger->info($e->getMessage()); $this->logger->info($e->__toString()); return $this->setResult(["success" => false, "id" => -1, "message" => "Error processing file. " . $e->getMessage(), "error" => 10]); } }
* { * "succes": "fichier upload" * } * * @apiErrorExample Error-Response: * HTTP/1.1 404 Not Found * { * "error": code error * } */ $app->post('/img/{id_product}', function ($request, $response, $id_product) use($app) { try { $yaml = new Parser(); $config = $yaml->parse(file_get_contents('config/config.yml')); $storage = new \Upload\Storage\FileSystem($config['parameters']["dir_files"] . 'product'); $file = new \Upload\File('file', $storage); //on passe son id en nom $file->setName($id_product["id_product"]); //fichier valide $file->addValidations(array(new \Upload\Validation\Mimetype(array('image/png', 'image/jpeg', 'image/pjpeg')), new \Upload\Validation\Size('5M'))); //check la validité du fichier pour supprimer le/les ancienne(s) image(s) if ($file->validate()) { foreach (glob($config['parameters']["dir_files"] . 'product/' . $id_product["id_product"] . '.*') as $oldFile) { unlink($oldFile); } } //on upload le fichier $file->upload(); //on ajoute son nom en base Capsule::table('PRODUCT')->where('id_product', $id_product["id_product"])->update(['image' => $file->getNameWithExtension()]); $response = $response->withJson(array("status" => array("succes" => "fichier upload")), 200);
public function get_m3u_data() { if (!$this->isAjax || $this->method != 'POST') { $this->app->abort(404, 'Page not found...'); } if ($no_auth = $this->checkAuth()) { return $no_auth; } $data = array(); $data['action'] = 'loadM3UData'; $data['data'] = array('channels' => array(), 'last_channel_number' => 0, 'free_number_exists' => 1); $error = $this->setLocalization('Upload failed'); $storage = new \Upload\Storage\FileSystem('/tmp', TRUE); $file = new \Upload\File('qqfile', $storage); try { // Success! $file->upload(); $obj = new M3uParser\M3uParser(); $m3u_data = $obj->parseFile($file->getPath() . '/' . $file->getNameWithExtension()); @unlink($file->getPath() . '/' . $file->getNameWithExtension()); $data['data']['last_channel_number'] = (int) $this->db->getLastChannelNumber(); if ($data['data']['last_channel_number'] + count($m3u_data) > 9999) { $data['data']['free_number_exists'] = (int) ($this->db->getAllChannels(array(), 'COUNT') + count($m3u_data) <= 9999); } foreach ($m3u_data as $entry) { $name = trim($entry->getName()); if (!mb_check_encoding($name, 'UTF-8')) { $name = mb_convert_encoding($name, 'UTF-8', array('CP1251')); } $data['data']['channels'][] = array('name' => $name, 'cmd' => trim($entry->getPath())); } $error = ''; } catch (\Exception $e) { // Fail! $data['msg'] = $error = $file->getErrors(); } $response = $this->generateAjaxResponse($data, $error); $json_string = json_encode($response); if (json_last_error() !== JSON_ERROR_NONE) { $error = $this->setLocalization('Error m3u parse. Check the file encoding. Required UTF-8 encoding.'); $json_string = json_encode(array('msg' => $error, 'error' => $error)); } return new Response($json_string, empty($error) ? 200 : 500); }
/** * Test won't overwrite existing file * * @expectedException \RuntimeException */ public function testWillNotOverwriteFile() { $storage = new \Upload\Storage\FileSystem($this->assetsDirectory, false); $file = new \Upload\File('foo', $storage); $file->upload(); }
function file_upload($location, $name) { $storage = new \Upload\Storage\FileSystem($this->basedir . 'img/' . $location, true); $file = new \Upload\File('file', $storage); // Optionally you can rename the file on upload $new_filename = $this->clean_str($name); $file->setName($new_filename); // Validate file upload // MimeType List => http://www.webmaster-toolkit.com/mime-types.shtml $file->addValidations(array(new \Upload\Validation\Mimetype(array('image/png', 'image/bmp', 'image/jpeg', 'image/pjpeg', 'image/gif')), new \Upload\Validation\Size('15M'))); // Access data about the file that has been uploaded $data = array('name' => $file->getNameWithExtension(), 'extension' => $file->getExtension(), 'mime' => $file->getMimetype(), 'size' => $file->getSize(), 'md5' => $file->getMd5(), 'dimensions' => $file->getDimensions()); // Try to upload file try { // Success! $file->upload(); return $data; } catch (\Exception $e) { // Fail! $errors = $file->getErrors(); $contex[0] = $e->getFile(); $contex[1] = $e->getLine(); $this->log->addError($e->getMessage(), $contex); } }
public function bytbildAction($user) { $filter_factory = new \Aura\Filter\FilterFactory(); $filter = $filter_factory->newValueFilter(); //$filter = $filter_factory->newSubjectFilter(); //$vUser = $this->profil->validateInput($user); $vUser = $filter->sanitize($user, 'alnum'); if ($vUser) { $vUser = $user; } else { echo "Användarnamnet är inte alfanumeriskt!"; } $path = ANAX_INSTALL_PATH . '/webroot/files'; $realPath = $this->url->create('files'); $storage = new \Upload\Storage\FileSystem($path); $file = new \Upload\File('profileImage', $storage); // Optionally you can rename the file on upload $new_filename = uniqid(); $file->setName($new_filename); $fileName = $file->getNameWithExtension(); $newPath = $realPath . '/' . $fileName; // Validate file upload // MimeType List => http://www.iana.org/assignments/media-types/media-types.xhtml $file->addValidations(array(new \Upload\Validation\Mimetype(array('image/png', 'image/jpg', 'image/jpeg', 'image/gif')), new \Upload\Validation\Size('5M'))); // Access data about the file that has been uploaded $data = array('name' => $file->getNameWithExtension(), 'extension' => $file->getExtension(), 'mime' => $file->getMimetype(), 'size' => $file->getSize(), 'md5' => $file->getMd5(), 'dimensions' => $file->getDimensions()); $this->anvandare->updateImage('anvandare', $vUser, ['username' => $vUser, 'profileimage' => $newPath]); // Try to upload file try { // Success! $file->upload(); $url = $this->url->create('profil/bild') . '/' . $vUser; $this->flash->message('success', 'Bilden uppdaterades'); $output = $this->flash->output(); $userImage = $this->anvandare->findImage($vUser); $this->views->add('profil/profileimage', ['output' => $output, 'userImage' => $userImage]); } catch (\Exception $e) { // Fail! // $errors = $file->getErrors(); $this->flash->message('danger', 'Något gick fel, ladda upp en png eller jpg-fil och försök igen...'); $output = $this->flash->output(); $userImage = $this->anvandare->findImage($vUser); $this->views->add('profil/profileimage', ['output' => $output, 'userImage' => $userImage]); } }
if ($app->request->post('uri')) { $video_id = str_replace('/videos/', '', $app->request->post('uri')); $vimeo->setToken($_SESSION['user.access_token']); $response = $vimeo->request('/me/watchlater/' . $video_id, array(), 'PUT'); $app->contentType('application/json'); echo '{"status": ' . json_encode($response['status']) . '}'; } }); $app->get('/upload', function () use($app, $vimeo) { $page_data = array(); $app->render('upload.php', $page_data); }); $app->post('/upload', function () use($app, $vimeo) { $vimeo->setToken('0ba6f164ff299c200d5552ae73c52063'); $storage = new \Upload\Storage\FileSystem('uploads'); $file = new \Upload\File('video', $storage); $new_filename = uniqid(); $file->setName($new_filename); $file->addValidations(array(new \Upload\Validation\Mimetype('video/mp4'), new \Upload\Validation\Size('25M'))); try { $file->upload(); } catch (\Exception $e) { $errors = $file->getErrors(); $app->flash('errors', $errors); } $new_filepath = 'uploads/' . $new_filename . '.' . $file->getExtension(); try { $vimeo->upload($new_filepath, false); } catch (\Exception $e) { $app->flash('errors', array('error uploading to Vimeo')); }
/** * [article_update 更新文章] * @return [type] [description] */ public function article_update($slug) { if (IS_POST) { //实例化上传类 $storage = new \Upload\Storage\FileSystem(__UPLOAD__); $file = new \Upload\File('foo', $storage); $fileName = $file->getNameWithExtension(); if (!empty($fileName)) { // Optionally you can rename the file on upload $new_filename = uniqid(); $file->setName($new_filename); // Validate file upload // MimeType List => http://www.webmaster-toolkit.com/mime-types.shtml $file->addValidations([new \Upload\Validation\Mimetype(['image/png', 'image/gif', 'image/jpeg', 'image/jpg']), new \Upload\Validation\Size('5M')]); // Access data about the file that has been uploaded $data = ['name' => $file->getNameWithExtension(), 'extension' => $file->getExtension(), 'mime' => $file->getMimetype(), 'size' => $file->getSize(), 'md5' => $file->getMd5(), 'dimensions' => $file->getDimensions()]; // Try to upload file try { // Success! $file->upload(); $arcData = ['title' => I('post.title'), 'thumb' => $data['name'], 'keywords' => I('post.keywords'), 'content' => I('post.content'), 'description' => I('post.description'), 'category_id' => I('post.category_id'), 'click' => I('post.click'), 'writer' => I('post.writer'), 'source' => I('post.source'), 'pubdate' => time()]; Article::where(['id' => $slug])->update($arcData); View::success('修改成功'); die; } catch (\Exception $e) { // Fail! $errors = $file->getErrors(); View::error($errors['0']); die; } } if (isset($_POST['del_img'])) { $arcData = ['title' => I('post.title'), 'keywords' => I('post.keywords'), 'thumb' => '', 'content' => I('post.content'), 'description' => I('post.description'), 'category_id' => I('post.category_id'), 'click' => I('post.click'), 'writer' => I('post.writer'), 'source' => I('post.source'), 'pubdate' => time()]; Article::where(['id' => $slug])->update($arcData); View::success('修改成功'); die; } else { $arcData = ['title' => I('post.title'), 'keywords' => I('post.keywords'), 'content' => I('post.content'), 'category_id' => I('post.category_id'), 'click' => I('post.click'), 'writer' => I('post.writer'), 'source' => I('post.source'), 'pubdate' => time()]; Article::where(['id' => $slug])->update($arcData); View::success('修改成功'); die; } } $arcData = Article::find($slug)->toArray(); //print_r($arcData); $topcate = Category::where(['pid' => 0, 'is_del' => 0])->get()->toArray(); //组合分类数据 foreach ($topcate as $k => $v) { $soncate = Category::where(['pid' => $v['id'], 'is_del' => 0])->get()->toArray(); $topcate[$k]['soncate'] = $soncate; } $allcate = $topcate; $this->smarty->assign('title', '修改文章_ISisWeb中文网后台管理_ISirPHPFramework'); $this->smarty->assign('cate', $allcate); $this->smarty->assign('arcData', $arcData); $this->smarty->display('Admin/Article/update.html'); // die(); // $this->view = View::make('/Admin/Article/update') // ->with('cate',$allcate) // ->with('arcData',$arcData) // ->with('title','修改文章_ISirWeb中文网后台'); }
/** * @expectedException \Upload\Exception */ public function testWillNotUploadIfInvalid() { $file = new \Upload\File('bad', $this->storage); $this->assertFalse($file->isValid()); $file->upload(); // <-- Will throw exception }
namespace surrogator; require '../vendor/autoload.php'; $cfgFile = __DIR__ . '/../data/surrogator.config.php'; if (!file_exists($cfgFile)) { $cfgFile = '/etc/surrogator.config.php'; if (!file_exists($cfgFile)) { err(500, "Configuration file does not exist.", "Copy data/surrogator.config.php.dist to data/surrogator.config.php"); exit(2); } } require $cfgFile; require __DIR__ . '/shib_attr.php'; $storage = new \Upload\Storage\FileSystem($rawDir, true); $file = new \Upload\File('profileFile', $storage); // Optionally you can rename the file on upload $mail = strtolower($shib_mail); $file->setName($mail); // Validate file upload // MimeType List => http://www.iana.org/assignments/media-types/media-types.xhtml $file->addValidations(array(new \Upload\Validation\Mimetype(array('image/png', 'image/jpeg')), new \Upload\Validation\Size('5M'))); // Access data about the file that has been uploaded $data = array('name' => $file->getNameWithExtension(), 'extension' => $file->getExtension(), 'mime' => $file->getMimetype(), 'size' => $file->getSize(), 'md5' => $file->getMd5(), 'dimensions' => $file->getDimensions()); // Try to upload file try { // Success! shell_exec('rm ' . __DIR__ . '/../raw/' . $mail . '.*'); $file->upload(); $output = shell_exec('php ' . __DIR__ . '/../surrogator.php'); $results = array('status' => 'ok', 'file_data' => $data, 'surroggator' => $output);