<p>You're missing the closing <code>}</code> for the if statement.  Add that in and it should work:</p>

<pre><code>craft()-&gt;on('assets.onBeforeSaveAsset', function(Event $event) {
    if ($event-&gt;params['isNewAsset'])
    {
        $asset = $event-&gt;params['asset'];
        $filename = StringHelper::randomString(8).'.'.$asset-&gt;getExtension();

        $asset-&gt;setAttribute('filename', $filename);
    }
});
</code></pre>

CC BY-SA 3.0
2017-10-06T06:15:42.450Z
The if closing bracket actually does exist in my code, it just got lost in copy and pasting somehow. My code looks exactly like what you provided.
justussimon91
CC BY-SA 3.0
2017-10-06T17:00:29.150Z
Looks like you don't need the call to `craft()->assets->storeFile($asset);` anymore.  Edited my answer...tested locally and works for me.
Brad Bell
CC BY-SA 3.0
2017-10-09T06:13:22.727Z
It still won't work, but at least I get a error printed to the logs now. Maybe you can make anything out of it? I adjusted my original post.
justussimon91
CC BY-SA 3.0
2017-10-05T14:24:51.487Z
2017-10-06T16:59:59.877Z
2017-10-06T16:59:59.877Z
Brad Bell
<p>I'm trying to rename a file before it is actually saved into Craft, by using the following code snippet in a plugin:</p>

<pre><code>craft()-&gt;on('assets.onBeforeSaveAsset', function(Event $event) {
        if($event-&gt;params['isNewAsset'])
        {
            $asset = $event-&gt;params['asset'];
            $filename = 'SOME_RANDOM_STRING'.$asset-&gt;getExtension();

            $asset-&gt;setAttribute('filename', $filename);

            craft()-&gt;assets-&gt;storeFile($asset);

    });
</code></pre>

<p>I found the snippet on some other question on this board, and while it seems to be correct, as soon as the above snippet is used files won't upload anymore. Within craft itself, the upload bar just stays there forever with nothing happening anymore, and when using a frontend ajax form to upload a file, the ajax request fails. However, there are no errors printed into the logfiles, so I really can't figure out what's causing the issue. As soon as I remove the above snippet again, uploads work fine again.</p>

<p>Any ideas?</p>

<p>EDIT:
After editing the code to what Brad provided, it still won't work, but at least the logfiles now show some actual error.</p>

<pre><code>2017/10/09 06:11:24 [error] [php] fopen(https://s3-eu-west-1.amazonaws.com/***/challenges/NZpnyFj5.jpg): failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden
 (/home/praktikant/www/x-challenge.info/craft/plugins/businesslogic/BusinessLogicPlugin.php:172)
Stack trace:
#0 /home/praktikant/www/x-challenge.info/craft/plugins/businesslogic/BusinessLogicPlugin.php(88): Craft\BusinessLogicPlugin-&gt;generateCopyright()
#1 unknown(0): Craft\BusinessLogicPlugin-&gt;Craft\{closure}()
#2 /home/praktikant/www/x-challenge.info/craft/app/framework/base/CComponent.php(567): call_user_func()
#3 /home/praktikant/www/x-challenge.info/craft/app/services/AssetsService.php(1174): Craft\AssetsService-&gt;raiseEvent()
#4 /home/praktikant/www/x-challenge.info/craft/app/services/AssetsService.php(224): Craft\AssetsService-&gt;onSaveAsset()
#5 /home/praktikant/www/x-challenge.info/craft/app/assetsourcetypes/BaseAssetSourceType.php(275): Craft\AssetsService-&gt;storeFile()
#6 /home/praktikant/www/x-challenge.info/craft/app/services/AssetsService.php(776): Craft\S3AssetSourceType-&gt;insertFileByPath()
#7 /home/praktikant/www/x-challenge.info/craft/app/fieldtypes/AssetsFieldType.php(273): Craft\AssetsService-&gt;insertFileByLocalPath()
#8 /home/praktikant/www/x-challenge.info/craft/app/models/BaseElementModel.php(912): Craft\AssetsFieldType-&gt;prepValueFromPost()
#9 /home/praktikant/www/x-challenge.info/craft/app/controllers/EntriesController.php(931): Craft\EntryModel-&gt;setContentFromPost()
#10 /home/praktikant/www/x-challenge.info/craft/app/controllers/EntriesController.php(446): Craft\EntriesController-&gt;_populateEntryModel()
#11 /home/praktikant/www/x-challenge.info/craft/app/framework/web/actions/CInlineAction.php(49): Craft\EntriesController-&gt;actionSaveEntry()
#12 /home/praktikant/www/x-challenge.info/craft/app/framework/web/CController.php(308): CInlineAction-&gt;runWithParams()
#13 /home/praktikant/www/x-challenge.info/craft/app/framework/web/CController.php(286): Craft\EntriesController-&gt;runAction()
#14 /home/praktikant/www/x-challenge.info/craft/app/framework/web/CController.php(265): Craft\EntriesController-&gt;runActionWithFilters()
#15 /home/praktikant/www/x-challenge.info/craft/app/framework/web/CWebApplication.php(282): Craft\EntriesController-&gt;run()
#16 /home/praktikant/www/x-challenge.info/craft/app/etc/web/WebApp.php(817): Craft\WebApp-&gt;runController()
#17 /home/praktikant/www/x-challenge.info/craft/app/etc/web/WebApp.php(287): Craft\WebApp-&gt;_processActionRequest()
#18 /home/praktikant/www/x-challenge.info/craft/app/framework/base/CApplication.php(185): Craft\WebApp-&gt;processRequest()
#19 /home/praktikant/www/x-challenge.info/craft/app/index.php(62): Craft\WebApp-&gt;run()
#20 /home/praktikant/www/x-challenge.info/public/index.php(19): require_once()
REQUEST_URI=/hochladen
</code></pre>

<p>The error seems to be related to the <code>fopen()</code> not being able to open the file saved to the S3 bucket. However, I don't really understand why because the files on the S3 bucket can be accessed just fine if they are uploaded without trying to rename them on <code>onBeforeSaveAsset</code>.</p>

CC BY-SA 3.0
2017-10-04T23:01:45.837Z
Open your browser's network tab when you upload the asset.  What status/response does the AJAX request come back with?
Brad Bell
CC BY-SA 3.0
2017-10-05T06:12:30.840Z
The whole XHR tab just literally states "no response data" if I select the URL I want to check. Remember that as soon as I remove the above snippet from the onBeforeSaveAsset service call, everything runs fine again.
justussimon91
<assets><plugins><php><events>
renaming a file in onBeforeSaveAsset won't work
# renaming a file in onBeforeSaveAsset won't work

(Asked by: username_0 on 2017-10-04)

I'm trying to rename a file before it is actually saved into Craft, by using the following code snippet in a plugin:
craft()->on('assets.onBeforeSaveAsset', function(Event $event) {
        if($event->params['isNewAsset'])
        {
            $asset = $event->params['asset'];
            $filename = 'SOME_RANDOM_STRING'.$asset->getExtension();

            $asset->setAttribute('filename', $filename);

            craft()->assets->storeFile($asset);

    });

I found the snippet on some other question on this board, and while it seems to be correct, as soon as the above snippet is used files won't upload anymore. Within craft itself, the upload bar just stays there forever with nothing happening anymore, and when using a frontend ajax form to upload a file, the ajax request fails. However, there are no errors printed into the logfiles, so I really can't figure out what's causing the issue. As soon as I remove the above snippet again, uploads work fine again.
Any ideas?
EDIT:
After editing the code to what Brad provided, it still won't work, but at least the logfiles now show some actual error.
2017/10/09 06:11:24 [error] [php] fopen(https://s3-eu-west-1.amazonaws.com/***/challenges/NZpnyFj5.jpg): failed to open stream: HTTP request failed! HTTP/1.1 403 Forbidden
 (/home/praktikant/www/x-challenge.info/craft/plugins/businesslogic/BusinessLogicPlugin.php:172)
Stack trace:
#0 /home/praktikant/www/x-challenge.info/craft/plugins/businesslogic/BusinessLogicPlugin.php(88): Craft\BusinessLogicPlugin->generateCopyright()
#1 unknown(0): Craft\BusinessLogicPlugin->Craft\{closure}()
#2 /home/praktikant/www/x-challenge.info/craft/app/framework/base/CComponent.php(567): call_user_func()
#3 /home/praktikant/www/x-challenge.info/craft/app/services/AssetsService.php(1174): Craft\AssetsService->raiseEvent()
#4 /home/praktikant/www/x-challenge.info/craft/app/services/AssetsService.php(224): Craft\AssetsService->onSaveAsset()
#5 /home/praktikant/www/x-challenge.info/craft/app/assetsourcetypes/BaseAssetSourceType.php(275): Craft\AssetsService->storeFile()
#6 /home/praktikant/www/x-challenge.info/craft/app/services/AssetsService.php(776): Craft\S3AssetSourceType->insertFileByPath()
#7 /home/praktikant/www/x-challenge.info/craft/app/fieldtypes/AssetsFieldType.php(273): Craft\AssetsService->insertFileByLocalPath()
#8 /home/praktikant/www/x-challenge.info/craft/app/models/BaseElementModel.php(912): Craft\AssetsFieldType->prepValueFromPost()
#9 /home/praktikant/www/x-challenge.info/craft/app/controllers/EntriesController.php(931): Craft\EntryModel->setContentFromPost()
#10 /home/praktikant/www/x-challenge.info/craft/app/controllers/EntriesController.php(446): Craft\EntriesController->_populateEntryModel()
#11 /home/praktikant/www/x-challenge.info/craft/app/framework/web/actions/CInlineAction.php(49): Craft\EntriesController->actionSaveEntry()
#12 /home/praktikant/www/x-challenge.info/craft/app/framework/web/CController.php(308): CInlineAction->runWithParams()
#13 /home/praktikant/www/x-challenge.info/craft/app/framework/web/CController.php(286): Craft\EntriesController->runAction()
#14 /home/praktikant/www/x-challenge.info/craft/app/framework/web/CController.php(265): Craft\EntriesController->runActionWithFilters()
#15 /home/praktikant/www/x-challenge.info/craft/app/framework/web/CWebApplication.php(282): Craft\EntriesController->run()
#16 /home/praktikant/www/x-challenge.info/craft/app/etc/web/WebApp.php(817): Craft\WebApp->runController()
#17 /home/praktikant/www/x-challenge.info/craft/app/etc/web/WebApp.php(287): Craft\WebApp->_processActionRequest()
#18 /home/praktikant/www/x-challenge.info/craft/app/framework/base/CApplication.php(185): Craft\WebApp->processRequest()
#19 /home/praktikant/www/x-challenge.info/craft/app/index.php(62): Craft\WebApp->run()
#20 /home/praktikant/www/x-challenge.info/public/index.php(19): require_once()
REQUEST_URI=/hochladen

The error seems to be related to the fopen() not being able to open the file saved to the S3 bucket. However, I don't really understand why because the files on the S3 bucket can be accessed just fine if they are uploaded without trying to rename them on onBeforeSaveAsset.

**Tags:** assets, plugins, php, events

> **Comments:**
> **username_1**: Open your browser's network tab when you upload the asset.  What status/response does the AJAX request come back with?  
> **username_0**: The whole XHR tab just literally states "no response data" if I select the URL I want to check. Remember that as soon as I remove the above snippet from the onBeforeSaveAsset service call, everything runs fine again.  

---

## 1 answers

### Answer by username_1 on 2017-10-05. Score: 1

You're missing the closing } for the if statement.  Add that in and it should work:
craft()->on('assets.onBeforeSaveAsset', function(Event $event) {
    if ($event->params['isNewAsset'])
    {
        $asset = $event->params['asset'];
        $filename = StringHelper::randomString(8).'.'.$asset->getExtension();

        $asset->setAttribute('filename', $filename);
    }
});

> **Comments:**
> **username_0**: The if closing bracket actually does exist in my code, it just got lost in copy and pasting somehow. My code looks exactly like what you provided.  
> **username_1**: Looks like you don't need the call to `craft()->assets->storeFile($asset);` anymore.  Edited my answer...tested locally and works for me.  
> **username_0**: It still won't work, but at least I get a error printed to the logs now. Maybe you can make anything out of it? I adjusted my original post.  

---

