views:

61

answers:

1

Hi guys is it possible to be able to retain an uploaded file AFTER its been uploaded I mean I'm building a compose email application. Users can upload files as attachments. AT times out of 10 uploaded files one of them isn't uploaded correctly or the submitted form is invalid the compose page would be displayed again however the user would ned to upload the file again this time. Is it possible to somehow maintain the uploaded files somewhere on the first upload and if the form is invalid - be able to display links to the file uploaded or so?

+1  A: 

Yes, just copy the files to an temporary folder and display the files as list which have been successfully uploaded. Then store the filenames inside hidden input fields (for example) and when the user submits the form again, you will be able to upload the new files and also retrieve the files that were uploaded previously.

Some pseudoish code:

/*
If $_POST request
    Loop through every file uploaded ($_FILES)
        Check for errors
        Save the file into a temporary directory
        Build an array of files successfully uploaded 

    Loop through previously uploaded files ($_POST['uploaded'])
        Append the filenames to the array of uploaded files

    Validate the rest of the form

    If no errors
        Move files from temporary location to the actual location
    Else
        Show the same form
        Print the filenames inside hidden input fields
            <input type="hidden" name="uploaded[]" value="filename.txt" />
        Show the user the list of files and allow deletion of files

    Rinse and repeat
*/
Tatu Ulmanen
you have completely forgot a garbage collection part. and using hidden fields is silly.
Col. Shrapnel
@Col. Shrapnel, ever heard of an simplified example? Noticed the `for example` part in my text regarding to the usage of hidden fields, which implies that hidden fields are not the only (or the best) way to solve this, merely the fastest to show? The example shows the basic steps one should take to accomplish a system like this, it is not meant to be a full blown implementation.
Tatu Ulmanen
well you fail to implement most non-obvious part - a garbage collection. while the rest of your code is just basic form handling from schoolbook
Col. Shrapnel