0 preface files uploaded by paperclip are stored in the public directory of the rails project by default. That is to say, if you can get the URL of the file, you can directly access/download the file, if you want to add access control to the file, you need to change the default upload location of paperclip. 1. Change the default upload position of paperclip. If there is a story class, each story has a cover, and the cover is an image, you can change the model definition as follows:
Class story <activerecord: Base has_attached_file: Cover,: styles =>{: small => "32x32" },: Path => ": rails_root/paperclip /: class/: attachment/: ID/: style/: FILENAME ",: url =>"/paperclip/: Class/: attachment/: ID/: style/: FILENAME "End
To modify the path and URL simultaneously, the URL is used by the rails app to obtain the image rendering page, and the path is the path in the entire host file system relative to the rails app server. The path and URL must be modified simultaneously. Here, set the directory for saving the paperclip upload file to the paperclip directory under the rails project root directory. 2. Add a controller to routes. RB:
Get "/paperclip/: Class/: attachment/: ID/: style/: FILENAME", to: "assets # Show"
Add the assets_controller.rb file:
Class assetscontroller <applicationcontroller def show CLS = Params [: Class]. singularize. capitalize. constantize asset = Cls. find Params [: Id] send_file asset. send (Params [: attachment]. singularize ). PATH (Params [: style]) endend
In the submitted parameter, Params [: Class] is in the plural form. Generally, the class definition is singular, such as story, and Params [: attachment] is also in the plural form. In the class definition, cover is singular, therefore, they must all be changed to singular. If the attachment defined in the class is in the plural form, the attachment does not need to be converted to a singular value here. Otherwise, a nomethod exception is thrown. Currently, all paperclip resources are controlled by assetscontroller, so it is very convenient to add before_filter, such as identity logon authentication, to it. After identity authentication is added, even if the user obtains the cover URL, the image cannot be accessed directly without logon.