Skip to content
Advertisement

Set order of uploaded images (JS, PHP)

My goal is to get a way to upload multiple images and also set in which order they should be displayed later on (it’s for an ecommerce website). I have an idea which seems to work. But I would like to know if there is a better way of doing this. Here is my code. Let’s assume the number of images is limited to 3.

  1. One input for multiple images.
  2. Preview images and make them sortable.
  3. Store the order in hidden inputs.
  4. Store the images in the filesystem.
  5. Add the path and order index of every image to the database.

HTML

JavaScript

JavaScript

JavaScript

JavaScript
JavaScript
JavaScript

I haven’t figured out yet how to limit the number of submitted images. But I saw a number of discussions about that, so I hope it will not be a problem.

PHP. The next step is done by means of PHP (CodeIgniter 4). I take the images, store them in my filesystem. Also I add the path to every image and its order index (taken from the hidden input) to the database. Later when a user will open certain product, the data will be taken from the database and ordered by order index. So basically my controller has this:

JavaScript

It would be perfect if I could upload multiple images at once and then not only reorder them but also be able to replace one of the images. If someone could share any ideas, I will appreciate it very much!

Advertisement

Answer

After long time I have returned to this project and made further research. So I would like to share my solution.

So I have decided that a convenient option will be to have only one input for multiple images. The user clicks it and chooses the needed images. If he needs to add more images after this, he clicks the same input again and the new images are added to the list. All images immediately appear as previews with the “delete” button. So if the user needs to replace one image, he can delete it, upload a new image and move it to the needed place.

The PHP code from my post does not require any changes. The work is done in Javascript. There are lots of lines of code, but a big part of them is simply for dynamic generating of previews. Please see the snippet.

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement