Problem with renaming image after upload

How can I rename an uploaded image, and set the new name in my model before saving the model?

It's quite clear how to save the uploaded image under a new name:

$objImage->strImage->saveAs($strDir.'newname.jpg');

but how can I set 'newname.jpg' in the model?

Use the

Quote

protected function beforeValidate($on) {

    $this->image = {the new name of the image}

}

in the model class

Quote

Use the

Quote

protected function beforeValidate($on) {

    $this->image = {the new name of the image}

}

in the model class

I've tried this already, but it doens't work, because $objImage->strIMage is containing the result of "CUploadedFile::getInstance($objImage, "strImage[$n]");"

EDIT:

if I do something like this:

$strImage = str_replace(' ', '-', $objImage->strImage->getName());

$objImage->strImage->saveAs($strDir.$strImage);

$objImage->strImage = $strImage;

$objImage->save();

the image (i.e. "image 1.jpg") gets renamed (to: "image-1.jpg"), but my model won't be saved to database. :frowning:

You should do this in beforeSave(). Otherwise, the validation will fail.

Quote

You should do this in beforeSave(). Otherwise, the validation will fail.

If I do so, I'll get an error:

"strImage must not be empty"

It's a bit more complex, because I'm building a BaseModel, which handles multiple image uploads for a model (i.e. "Teaser" gets an additional Model "TeaserImage").

Everything works fine, except the renaming of uploaded files :frowning:

You can also declare a public member in the model class to store the uploaded file instance. Leave strImage to store file name only. Then you need to validate on that public member instead of strImage.

Quote

You can also declare a public member in the model class to store the uploaded file instance. Leave strImage to store file name only. Then you need to validate on that public member instead of strImage.

Yes, I think I've got it working now:

The trick was, that I validated strImage in function "beforeSave", and then in function "afterSave", when I call "$objImage->save(false)" I turned out validaten, because at this point objImage is already valid.

Now I can set strImage (bevor saving the image) like this:

$objFile = $objImage->strImage;

$strImage = $this->getCleanFileName($objFile->getName());

$objImage->strImage = $strImage;

$objFile->saveAs($strDir.$strImage);

$objImage->save(false);