You can create a POST request via Ajax to the assets/deleteFile
(Craft 2) / assets/delete-asset
(Craft 3) controller action:
Craft 2:
$('#delete-file').click(function() {
var data = {
fileId: 100
};
$.post('/actions/assets/deleteFile', data, function(response) {
// ...
});
});
Craft 3:
$('#delete-file').click(function() {
var data = {
assetId: 100
};
$.post('/actions/assets/delete-asset', data, function(response) {
// ...
});
});
That controller action will require that the user is logged-in with a user account that has the “Remove files” permission on the asset source that the file belongs to. Granting that permission to a user will give them the ability to delete any file within that asset source though - not just their own. So this is probably not a good idea.
A better way of doing this would be to write a module that provides its own controller that does its own permission checking and handles the file deletion. It would look something like this:
Craft 2:
class MyController extends BaseController
{
public function actionDeleteFile()
{
$this->requireAjaxRequest();
$fileId = craft()->request->getRequiredPost('fileId');
$file = craft()->assets->getFileById($fileId);
if (!$file)
{
throw new Exception('Could not find a file with the ID '.$fileId);
}
// Make sure that it's within a folder with the same name as the user's username
if ($file->getFolder()->name != craft()->userSession->getUser()->username)
{
throw new HttpException(403);
}
$response = craft()->assets->deleteFiles($fileIds);
$this->returnJson($response->getResponseData());
}
}
Craft 3:
use Craft;
use craft\web\Controller;
use yii\web\BadRequestHttpException;
use yii\web\ForbiddenHttpException;
use yii\web\Response;
class MyController extends Controller
{
public function actionDeleteFile(): Response
{
$this->requireAcceptsJson();
$assetId = Craft::$app->request->getRequiredBodyParam('fileId');
$asset = Craft::$app->assets->getAssetById($assetId);
if (!$asset) {
throw new BadRequestHttpException('Invalid asset ID: ' . $assetId);
}
// Make sure that it's within a folder with the same name as the user's username
if ($asset->getFolder()->name != Craft::$app->user->getIdentity()->username) {
throw new ForbiddenHttpException('Not permitted to delete asset ' . $assetId);
}
$success = Craft::$app->elements->deleteElement($asset);
return $this->asJson([
'success' => $success,
]);
}
}
With that in place, you’d just need to update your JavaScript to point to your deleteFile
/delete-file
action instead of Craft’s.