ORM-based file upload package for php.

Related tags

Files stapler
Overview

#Stapler Build Status Latest Stable Version Total Downloads Latest Unstable Version License

Note: If you've previously been using this package, then you've been using it with Laravel. This package is no longer directly coupled to the Laravel framework. As of 1.0.0, Stapler is now framework agnostic. In order to take advantage of the Laravel specific features provided by the previous Beta releases (service providers, IOC container, commands, migration generator, etc) , I've created a separate package specifically for the purpose of using Stapler within Laravel: Laravel-Stapler. If you're using Stapler inside a Laravel application I strongly recommend you use this package (it will save you a bit of boilerplate).

Stapler is a php-based framework agnostic file upload package inspired by the Ruby Paperclip gem. It can be used to add file file uploads (as attachment objects) to your ORM records. While not an exact duplicate, if you've used Paperclip before then you should feel quite comfortable using this package.

Stapler was created by Travis Bennett.

Requirements

Stapler currently requires php >= 5.4 (Stapler is implemented via the use of traits).

Installation

Stapler is distributed as a composer package, which is how it should be used in your app.

Install the package using Composer. Edit your project's composer.json file to require codesleeve/stapler.

  "require": {
    "codesleeve/stapler": "1.0.*"
  }

About Stapler

Stapler works by attaching file uploads to database table records. This is done by defining attachments inside the table's corresponding model and then assigning uploaded files (from your forms) as properties (named after the attachments) on the model before saving it. Stapler will listen to the life cycle callbacks of the model (after save, before delete, and after delete) and handle the file accordingly. In essence, this allows uploaded files to be treated just like any other property on the model; stapler will abstract away all of the file processing, storage, etc so you can focus on the rest of your project without having to worry about where your files are at or how to retrieve them.

Key Benefits

  • Modern: Stapler runs on top of php >= 5.4 and takes advantage of many of the new features provided by modern php (traits, callable typehinting, etc).
  • Simple: Traditionally, file uploading has been known to be an arduous task; Stapler reduces much of the boilerplate required throughout this process. Seriously, Stapler makes it dead simple to get up and running with file uploads (of any type).
  • Flexible: Stapler provides an extremely flexible cascading configuration; files can be configured for storage locally or via AWS S3 by changing only a single configuration option.
  • Scalable: Storing your assets in a central location (such as S3) allows your files to be accessable by multiple web instances from a single location.
  • Powerful: Stapler makes use of modern object oriented programming patterns in order to provide a rock solid architecture for file uploading. It's trait-based driver system provides the potential for it to work across multiple ORMS (both Active Record and Data Mapper implementations) that implement life cycle callbacks.

Documentation

Comments
  • Make the __wakeup() method public

    Make the __wakeup() method public

    It does not seem common to implement __wakeup() privately. I've been having issues with the Stapler S3 storage adapter where this method can't be called because it's private.

    Is there a reason S3ClientManager's wakeup method is private?

    opened by grough 15
  • Error in StaplerServiceProvider.php

    Error in StaplerServiceProvider.php

    Getting this error when running composer update command. ??

    {"error":{"type":"Symfony\Component\Debug\Exception\FatalErrorException","message":"syntax error, unexpected '['","file":"/home/damascu1/drccweb/vendor/codesleeve/stapler/src/Codesleeve/Stapler/StaplerServiceProvider.php","line":118}}{"error":{"type":"Symfony\Component\Debug\Exception\FatalErrorException","message":"syntax error, unexpected '['","file":"/home/damascu1/drccweb/vendor/codesleeve/stapler/src/Codesleeve/Stapler/StaplerServiceProvider.php","line":118}}Script php artisan clear-compiled handling the post-update-cmd event returned with an error

    opened by GDLaw 13
  • Issue when deleting files from S3

    Issue when deleting files from S3

    I just upgraded my app from L4 to L5 and encountered an issue when deleting a file from S3. An exception is thrown when validating the delete request to S3:

    {"error":{"type":"InvalidArgumentException","message":"Found 1 error while validating the input provided
     for the DeleteObjects operation:\n[Delete] is missing and is a required parameter","file":"\/www
    \/htdocs\/vendor\/aws\/aws-sdk-php\/src\/Api\/Validator.php","line":38}}
    

    Which would seem very weird to me. I did check the message (see attachment) and as far as I can see, the [Delete] component is actually available. Any idea what this could be?

    screen shot 2015-09-29 at 16 50 23

    I'm using the following stack:

    • L5.1
    • laravel-Stapler 1.0.05
    • stapler 1.0.06 aws/aws-sdk-php 3.4.0

    Much appreciated

    opened by elimentz 12
  • resize only if original is bigger than requested style

    resize only if original is bigger than requested style

    Hello,

    I would like to know if there is an easy way to resize an image only if it is bigger than the size defined in the requested style. If the image is smaller, we just do not touch it.

    Thank you for your help Regards,

    opened by jbajou 11
  • Add ability to set image quality

    Add ability to set image quality

    The image quality of generated images isn't good as it should be so I decided to add a simple option, which allows you to set the quality of every single style with a simple @PERCENT postfix:

    $this->hasAttachedFile('image', array(
        'styles' => array(
            'thumbnail' => '70x70@95',
        ),
    ));
    
    opened by bonzai 11
  • Filename Slug

    Filename Slug

    This package is extremely useful, however still miss something. The Laravel possuim one function to create slugs, Str::slug() and I think it would be interesting to add this option to rename the images, that way it would be possible to follow a more defined pattern.

    $this->hasAttachedFile('image', array(
        'styles' => array(
            'slug' => true,
        ),
    ));

    In this case, something like Image Name_test.jpg would look like image-name-test.jpg

    opened by AngelinDark 10
  • Fix MIME detection and too long URL names

    Fix MIME detection and too long URL names

    This PR fixes a condition where the file attachment would fail to save in the filesystem because the filesystem name was derived from the URL basename that was too long for the filesystem to support.

    It also fixes a small issue where hash anchors in URLs would cause file extensions from pathinfo() to be incorrect

    opened by benallfree 9
  • Considerable performance problems using S3 backend

    Considerable performance problems using S3 backend

    I'm running stapler with a S3 backend and since implementing stapler I've noticed considerable lag in my application. After running xhprof over my laravel app and digging my way down through the rabbit hole I found out that for every attachment->url() call stapler seems to do a S3->bucketExists() call. This seems to generate a guzzle request over the S3 API to check if the bucket exists. When doing this for say 50 images on a page this will result in a lot of curl requests and is really slowing the application down.

    What is your opinion on this?

    opened by tomvo 9
  • [Help!]

    [Help!] "Permission denied" despite chmodded 0777 upload directory

    Im currently trying to incorporate a small gallery system into my application. Users can upload pictures to galleries and the pictures are getting resized to 3 different sizes for the thumbnail view, medium view and full view.

    <?php
    
    class Picture extends Eloquent {
        use \Codesleeve\Stapler\Stapler;
    
        protected $table = "user_pictures";
    
    
        public function __construct(array $attributes = array())
        {
            $this->hasAttachedFile('picture', [
                'styles' => [
                    'full' => '512x512',
                    'medium' => '256x256#',
                    'thumb' => '96x96#',
                ],
                'url' => '/uploads/images/:attachment/:style/:id_partition/:filename',
                'keep_old_files' => true
            ]);
    
            parent::__construct($attributes);
        }
    
        public function user()
        {
            return $this->belongsTo('User');
        }
    
    }
    

    My upload part of my function looks like this:

    $gallery = Gallery::find($id); // we get this through POST 
    $file = Input::file('file');
    
    $picture = new Picture;
    $picture->picture = $file;
    
    if ($gallery->pictures()->save($picture))
    {
        return Response::json('success', 200);
    
    } else {
        return Response::json('error', 400);
    }
    

    The image gets added to the database correctly and the uploads/ folder is 0777-chmodded as well. So no big deal there. However, the real problem I'm having is completely unclear to me:

    {
      "error":
      {
        "type": "Imagine\\Exception\\RuntimeException",
        "message": "imagejpeg(.IMG_0014.JPG): failed to open stream: Permission denied",
        "file": "\/Users\/spaceemotion\/dev\/laravel\/vendor\/imagine\/imagine\/lib\/Imagine\/Gd\/Image.php",
        "line": 691
      }
    }
    

    The php-tmp folder is writable as well, I tested that through other applications.

    Why do I still get a permission denied? What am I doing wrong?

    opened by spaceemotion 9
  • store more than one file with a single record

    store more than one file with a single record

    What is the best method to store multiple files with a single record. I have a need to store an image, an mp3, and an mp4 file and associate them with a single record. I don't really need a one-many relationship since there will never be more than one of each type of file being stored. My implementation works great if I just select one file with my form, however, if I select more than one the save function errors out with this error:

    Illuminate \ Database \ QueryException SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null (SQL: insert into sermons (title, subtitle, speaker, desc, msgdate, updated_at, created_at) values (, , , , , 2014-01-14 23:46:08, 2014-01-14 23:46:08))

    It's like it looses the reference to the instance of the newly created record. Here is the code from the function that handles adding a new record:

    public function handleCreate()
    {
        //handle create form submission
        $sermon = new Sermon;
        $sermon->title = Input::get('title');
        $sermon->subtitle = Input::get('subtitle');
        $sermon->speaker = Input::get('speaker');
        $sermon->desc = Input::get('desc');
        $sermon->msgdate = Input::get('msgdate');
        $sermon->imgfile = Input::file('imgfile');
        $sermon->mp3file = Input::file('mp3file');
        $sermon->mp4file = Input::file('mp4file');  
        $sermon->save();
    
        return Redirect::action('SermonsController@index');
    }
    

    I've looked for documentation on this but just cannot seem to find any. Any help would be greatly appreciated.

    opened by GDLaw 9
  • Use single table and set as relationship

    Use single table and set as relationship

    Hi

    I think it would be a great addition to use Stapler as a single table, e.g managed_files. The table would include a morphTo relationship to have multiple model types create a relation to it. Other models would then need morphMany or morphOne.

    The hereto described structure can be quite easily implemented, however pushing a file from a model to its managed_files relationship seems to be impossible at the moment..

    A code example:

    Let's say the managed_files table looks like this:

    $table->increments('id');
    $table->morphs('model');
    $table->string('file_file_name')->nullable();
    $table->integer('file_file_size')->nullable();
    $table->string('file_content_type')->nullable();
    $table->timestamp('file_updated_at')->nullable();
    

    The ManagedFile model:

    class ManagedFile extends Eloquent {
        public function model() {
            $this->morphTo();
        }
    }
    

    Another model, let's say User:

    class User extends Eloquent {
        public function __construct() {
            $this->hasAttachedFile('avatar[file]');
        }
        public function avatar() {
            $this->morphOne('ManagedFile', 'model');
        }
    }
    

    No matter how I try to feed hasAttachedFile with the uploaded file data, it still tries to find the corresponding columns in the User table instead of in the related model table.

    I don't know a lot about the internals of Stapler, but a quick suggestion may be to have hasAttachedFile support a parameter for setting a custom defined table and/or base column name.

    This way the file can be called as $user->avatar->file->url() or if a custom getAttribute method or presenter has been set still as $user->avatar->url(). Moreover as the hasAttachedFile is still set in the related model (User), model specific configurations can still be set.


    Note: the idea about using a single table originates from Drupal.

    opened by Propaganistas 8
  • Video From Cloudinary to S3

    Video From Cloudinary to S3

    Hello. We are currently using https://github.com/CodeSleeve/stapler for image uploads.

    But now we want to support uploading videos. This videos are processed by Cloudinary so basically we get 4 video URLs with different qualities.

    We want to save these videos to S3.

    Does https://github.com/CodeSleeve/stapler support this?

    opened by xmarkclx 0
  • Original image file not always uploaded to S3 (but styles are)

    Original image file not always uploaded to S3 (but styles are)

    I have this problem that occasionally some original image files are not saved to AWS S3. Most of the time everything works fine and it's maybe one file in 10000, but it happens semi-regularly (we currently have millions of files in S3, as stapler attachments, so it has happened quite a few times). What's weird is that some image styles are uploaded, but not the original. And it's not always the same styles, sometimes only one or two, sometimes everything but the original. This all seems to happen completely silently, since I can not find anything in any logs regarding the files. I haven't found any pattern for this and I'm not sure how to further test this. There doesn't seem to be any pattern to it.

    So this is as much a bug report as it is an open question for any ideas that could help me better track down this issue to get to the bottom of it?

    opened by teeli 0
  • :attachment interpolation & updates to Inflector pluralization

    :attachment interpolation & updates to Inflector pluralization

    A consideration for a future update might be to stop using Inflector pluralization on :attachment interpolation when creating the location for files. The Inflector package is routinely getting updates to how certain words are pluralized and when those updates are pulled into a project with Stapler, it can change Stapler's construction of file locations.

    For example, a project with an attachment named "audio" was formerly stored in /audios/[id]/[style]/[filename], but in Inflector v1.3, the pluralization for "audio" was changed to "audio" (instead of "audios"), which resulted in Stapler expecting files to be located at /audio/[id]/[style]/[filename]; breaking the connection to those files.

    It may be a better approach to interpolate :attachment with the attachment name as specified on the model, rather than pluralizing it. And/or allow for the plural form to be specified on the model.

    opened by ccwittwer 0
  • S3

    S3 "Error retrieving credentials from the instance profile metadata server" when using url() method

    Had said problem using laravel 5, stapler and laravel-stapler with S3 (outside EC2), and thought to report my 5c here in case it's a pain for someone else.

    What resolved the issue for me was moving key & secret under a credentials array: From

    's3_client_config' => [
        'key' => '',
        'secret' => '',
        'region' => '',
        'scheme' => 'http',
    ],
    

    to

    's3_client_config' => [
        'credentials' => [
            'key' => '',
            'secret' => '',
        ],
        'region' => '',
        'scheme' => 'http',
    ],
    

    and changing Validator.php's validateS3Options() to validate the changed options instead. (Naturally, i also updated the config file values.)

    opened by Hitunen 0
  • Laravel 5.5 Support

    Laravel 5.5 Support

    This change is not backwards compatible with this package. This is due to the override of the getAttributes() model method. If the attribute values aren't strings, the query builder can't bind them properly and you get an "Object could not be converted to string" message.

    This looks like it's been in the EloquentTrait for quite a long time, since https://github.com/CodeSleeve/stapler/pull/94/commits/86fd1db830a837c189384dad0f9c6eed325b3d8d. What does overriding that method actually provide though? Doesn't the accessor for the field still exist?

    Edit: Sorry I didn't bring this issue up in the laravel stapler repo, but this is the repo that contains the EloquentTrait class

    opened by austenc 4
FIle Uploader is a php package to aid fast , easy and safe file upload

FILE UPLOADER FIle Uploader is a php package to aid fast , easy and safe file upload installation composer require codad5/file-helper Features Fast an

Aniezeofor Chibueze Michael 2 Sep 3, 2022
Upload File Library For PHP ( Simple & Easy User )

Upload File Library For Backend/ServerSide PHP ( Simple & Easy For Use ), Support Multiple Upload

Lamhot Simamora 1 Oct 12, 2021
Basic anonymous and registered upload storage for temporary share file self hosted.

TMPShareX Basic anonymous and registered upload storage for temporary share file self hosted. Server Requirement PHP 7.4.8 [Support PHP 8] Nginx 1.19.

Sandy Hermansyah 1 Feb 3, 2022
This package used to upload files using laravel-media-library before saving model.

Laravel Media Uploader This package used to upload files using laravel-media-library before saving model. In this package all uploaded media will be p

Ahmed Fathy 312 Dec 12, 2022
This project is a demo for Media-Upload package:

??️ Media-Upload-Demo This project is a demo for Media-Upload package: ?? Installation guide As always you need to: composer install Then npm install

Mohamed Hafidi 9 Jan 9, 2023
A web based file manager,web IDE / browser based code editor

KodExplorer Update to kodbox: https://github.com/kalcaddle/kodbox Download | Demo It is recommended to use a new design upgrade product:kodbox 该项目处于维护

warlee 5.8k Jan 3, 2023
PictShare is an open source image, mp4, pastebin hosting service with a simple resizing and upload API that you can host yourself.

PictShare is an open source image, mp4, pastebin hosting service with a simple resizing and upload API that you can host yourself.

Haschek Solutions 709 Jan 3, 2023
kodbox is a file manager for web. It is a newly designed product based on kodexplorer.

kodbox is a file manager for web. It is a newly designed product based on kodexplorer. It is also a web code editor, which allows you to develop websites directly within the web browser.You can run kodbox either online or locally,on Linux, Windows or Mac based platforms

warlee 1.2k Jan 7, 2023
Watch changes in the file system using PHP

Watch changes in the file system using PHP This package allows you to react to all kinds of changes in the file system. Here's how you can run code wh

Spatie 170 Dec 25, 2022
File manager module for the Lumen PHP framework.

Lumen File Manager File manager module for the Lumen PHP framework. Please note that this module is still under active development. NOTE: Branch 5.1 i

Digia 40 Aug 20, 2022
Gotipath Storage is a file storage library for PHP. It provides one interface to interact with FTP/SFTP.

Gotipath Storage is a file storage library for PHP. It provides one interface to interact with FTP/SFTP. When you use this package, you're protected from vendor lock-in, That mean you can connect to any FTP/SFTP storage. Also it's comes with base URL option to connect Gotipath CDN.

Gotipath 2 Nov 3, 2021
PHPProject is a library written in pure PHP that provides a set of classes to write to different project management file formats

PHPProject PHPProject is a library written in pure PHP that provides a set of classes to write to different project management file formats, i.e. Micr

PHPOffice 192 Dec 17, 2022
Detects file type by filename or content and generates correct mimetype.

FileTypeDetector Files type detector based on file name extension or file content (binary content). Usage Installation Supported formats Usage File Ty

Sergey 31 Oct 6, 2022
Uguu is a simple lightweight temporary file host with support for drop, paste, click and API uploading.

Uguu What is Uguu? Uguu is a simple lightweight temporary file hosting and sharing platform, but can also be used as a permanent file host. Features O

Eric Johansson (neku) 547 Dec 28, 2022
🛬🧾 A PHP8 TacView ACMI file format parser

A PHP8 TacView ACMI file format parser This package offers parsing support for TacView ACMI flight recordings version 2.1, it follows the standard des

Ignacio Muñoz Fernandez 1 Jan 18, 2022
Creating a file uploader with Laravel

File-Uploader File uploader is a simple group of restful APIs built in Laravel to upload file into a server and remove the file from that server. Tool

AmirH.Najafizadeh 4 Jul 31, 2022
Media gallery with CKEditor, TinyMCE and Summernote support. Built on Laravel file system.

Documents ・ Installation ・ Integration ・ Config ・ Customization ・ Events ・ Upgrade ・ Demo ・ FAQ Features File upload and management Uploading validati

UniSharp 1.9k Jan 1, 2023
Simple file uploading, Pomf like

Pomf-0x80 Simple file uploading, Pomf like. Features One click uploading, no registration required IPFS Upload + Pin A minimal, modern web interface D

Iqbal Rifai 4 Apr 28, 2022
Private file storage and share with user build with laravel and vue inspired by google drive

LaravelDrive is a file storage system that allows store private file and share with users build wiht laravel and vue inspired by google drive. Laravel

Shahadat Hossain 70 Dec 22, 2022