Skip to content

Instantly share code, notes, and snippets.

@boboldehampsink
Last active December 26, 2015 20:49
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boboldehampsink/7211614 to your computer and use it in GitHub Desktop.
Save boboldehampsink/7211614 to your computer and use it in GitHub Desktop.
Enable this plugin to connect <input type="file" name="fields[yourField]" /> as asset to yourField
<?php
namespace Craft;
class AssetUploadPlugin extends BasePlugin
{
function getName()
{
return Craft::t('Upload assets on the front-end');
}
function getVersion()
{
return '2.0';
}
function getDeveloper()
{
return 'Bob Olde Hampsink';
}
function getDeveloperUrl()
{
return 'http://www.itmundi.nl';
}
function init() {
// Only works on the front-end
if(craft()->request->isSiteRequest()) {
// Trigger when an entry is saved
craft()->on('entries.onSaveEntry', function(Event $event) {
craft()->assetUpload->process(ElementType::Entry, $event->params['entry']);
});
// Trigger when a user profile is saved
craft()->on('users.onSaveProfile', function(Event $event) {
craft()->assetUpload->process(ElementType::User, $event->params['user']);
});
}
}
}
<?php
namespace Craft;
class AssetUploadService extends BaseApplicationComponent
{
static private $inEvent = false;
public function process($type, $entry) {
// Only trigger when files are attached in the initial post
if(isset($_FILES) && !self::$inEvent) {
// Make sure saveEntry event only gets fired once
self::$inEvent = true;
// Loop trough filefields
foreach($_FILES as $files) {
if(is_array($files['name'])) {
foreach($files['name'] as $index => $file) {
// Make sure it's always an array
if(!is_array($file)) {
$file = array($file);
}
// Can have multiple files, loop trough
foreach($file as $key => $item) {
// Find in which upload source the file belongs
// TODO: multiple upload sources
$folderId = end(explode(':', craft()->fields->getFieldByHandle($index)->settings['sources'][0]));
$sourceId = craft()->assets->getFolderById($folderId)->sourceId;
// Find the path to the upload source
$uploadDir = craft()->assetSources->getSourceById($sourceId)->settings['path'];
// Rename file if necessary - use the same conflict resolution Craft uses
$i = 1;
$newpieces = explode(".", $item);
$frontpath = str_replace('.'.end($newpieces),'',$item);
while(file_exists($uploadDir.$item)) {
$item = $frontpath.'_'.$i.'.'.end($newpieces);
$i++;
}
// move file from temp to assets dir
if(move_uploaded_file($files['tmp_name'][$index][$key], $uploadDir.$item)){
// Create new AssetFile Model
$asset = new AssetFileModel();
$asset->sourceId = $sourceId;
$asset->folderId = $folderId;
$asset->filename = IOHelper::getFileName($item);
$asset->kind = IOHelper::getFileKind(IOHelper::getExtension($item));
$asset->size = filesize($uploadDir.$item);
$asset->dateModified = IOHelper::getLastTimeModified($uploadDir.$item);
if ($asset->kind == 'image')
{
list ($width, $height) = getimagesize($uploadDir.$item);
$asset->width = $width;
$asset->height = $height;
}
// Index file
craft()->assets->storeFile($asset);
// Update entry with asset
$entry->getContent()->setAttributes(array(
$index => array(@$asset->id)
));
// If entry
if($type == ElementType::Entry) {
// Save entry
craft()->entries->saveEntry($entry);
// If user
} elseif($type == ElementType::User) {
// Save profile
craft()->users->saveProfile($entry);
}
}
}
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment