Need to allow users to sort file order
I have a website where an admin can login and upload photos. All the images ar开发者_Python百科e placed in a directory and then on another page, i am cycling through the images and displaying them. The client has asked if there is a way to move the images around and place them in any order they want.
Now looking at the site, i'm not sure what order the files are even being displayed. They are definitely not in alphabetical order by filename.
I basically have 2 questions
- Is there a standard way that files are sorted or grabbed by using scandir?
- What is a good solution to allowing a user to sort the photos?
The way they are sorted depends on the filesystem and is not usually guaranteed to be consistent.
You will need to store the desired order somewhere. There are 3 ways I see to do this.
Use a database that stores a desired order and the filename. You can then get a list of filenames sorted by order. If new items are added to the folder, they will not initially have an order. You will need to set the order when they are added.
Soft the files by filename. When the user resorts the files, you will then need to rename them. The easiest way would be to rename them by their index in the desired order.
Use an index file. This would be similar to the database option, but would have a text file in each directory that stores the sorting information. When the user updates the order, you can place all the filenames into the index file in the desired order. You can then just load the index file and display the files in order. If a new file is not in the index file, you can just add it to the end.
Because storing file info in the database creates redundancy and thus adds unreliability, I'd go for a special file naming protocol. Let's say you have a.png and b.png, store them as 00001_b.png and 00002_a.png. When showing the files in your user interface: sort files alphabetically after scanning the directory, then remove the prefixes from the names. For simplicity, make the prefix a fixed length.
P.S. reordering is simple; in case you want to swap 00002_a.png and 00001_b.png you will have to:
- rename 00002_a.png to 00001_a.png
- rename 00001_b.png to 00002_b.png
精彩评论