0

My website allows a user to upload images. I'm stuck between two situations: whether I should upload the image immediately after it's selected, or upload the image after clicking the submit button.

I decided that uploading the image immediately makes a little more sense for my website, however, I ran into another issue.

As it stands, I want to have each image's name being the id of the post (for example: 500.png). However, if I upload the image before the user clicks submit, how would I name the image in this way (since I can't get the insert id when the user presses submit)?

user3390776
  • 61
  • 2
  • 7
  • If there is no id created, it can't assign a value to the image. You'd have to save the record to get the id first. Alternatively, you could rename the image after the record is saved to the id if you wish to save the image immediately upon selection. – Jack Mar 13 '14 at 19:38
  • you can use $('input[type=file]').change(function({$('form').submit(); }); to submit without using submit button. – NEO Mar 13 '14 at 19:40
  • Simply store the images in a separate table and store a foreign key to the image table instead of the image's file name. – Michael Benjamin Mar 13 '14 at 23:40

1 Answers1

0

Each time you upload an image, store the image in a separate table, with one column of the time at which the image is uploaded; and another column to indicate whether the image is attached to a post. You may use postid for this column.

When an image is auto uploaded, you can populate a hidden input field to store the auto ID of the image, and forward it to the post creation handler. The newly created post will have an ID. Save this in the postid column in the image. Now your image filename is using the imageid, not postid, but it's okay. If you really want to change the image name after the post name, upload the original image as img_###.png; then rename it to *.png, where ### is the image ID, and * is the post id. The img_ prefix is necessary to avoid name conflict. Again, this is not necessary. Image ID is just fine.

Finally you can set up a cron job to delete the image files and records that are uploaded a while ago but without a post ID. This will purge all the auto uploaded images without a submitted form.

You do have to take care of image upload racing condition. What if your image is still being uploaded, and someone clicks on the form post button already?

Schien
  • 3,493
  • 1
  • 13
  • 27