FileUpload and sendFile rename files

I’m uploading file as part of a view and renaming them to numeric filenames for security reasons. In my model, I generate a new filename for when the user chooses to access the file.

So in my controller I presently do something like

return \Yii::$app->response->sendFile($model->Filename);

where Filename is the numeric filename which is stored on the server

My question is, how can use sendFile() but give the file a new name for downloading by the user.

Say, in my system (both saved physically and in the db) the file is known as 123.jpg ($model->Filename), but I want it to show up to the user a castle.jpg (the proper name will come from $model->SaveFilename)?

Do I have to resave the file to the new name (make a duplicate) just to be able to serve it to them? Am I going about this the wrong way?

See the signature of this method - Response::sendFile($filePath, $attachmentName = null, $options = [])

$attachmentName - the file name shown to the user. If null, it will be determined from $filePath.

When in doubt always look at the code of method you are using. If the method does not offer what you seek scroll through the class code, maybe there is a different one that does. If nothing is found search for tips in documentation, then google it. Asking a question and waiting for reply should be the last thing in this process because it’s relatively slow way of getting the answer.

Thank you Bizley!

I have had a hard time with the documentation. I don’t know why, but I often read, re-read, re-read, … and just never understand. That said, the more I develop, I am finally starting to see the light and the end of the tunnel and some of it is starting to make sense now. I will endeavor to check it (as I did not in this instance and should have!).

Thank you for taking the time to help me with my problem and guide me. It is greatly appreciated!!!

1 Like