Database Reference
In-Depth Information
20.8. Processing File Uploads
Problem
You want to permit files to be uploaded to your web server and stored in your database.
Solution
Present the user with a web form that includes a file field. When the user submits the
form, extract the file and store it.
Discussion
One special kind of web input is an uploaded file. A file is sent as part of a post request,
but it's handled differently from other post parameters because a file is represented by
several pieces of information such as its contents, its MIME type, its original filename
on the client, and its name in temporary storage on the web server host.
To handle file uploads, you must send a special kind of form to the user; this is true no
matter what API you use to create the form. When the user submits the form, the
operations that check for and process an uploaded file are API-specific.
To create a form that enables files to be uploaded, the opening <form> tag should specify
the post method and must also include an enctype (encoding type) attribute with a
value of multipart/form-data :
<form method= "post" enctype= "multipart/form-data" action= " script_name ">
If the form uses the application/x-www-form-urlencoded encoding type, file uploads
will not work properly.
To include a file upload field in the form, use an <input> element of type file . For
example, this element presents a 60-character file field named upload_file :
<input type= "file" name= "upload_file" size= "60" />
The browser displays this field as a text input box into which the user can enter the name
manually. It also displays a Browse button that enables the user to select the file via a
standard file-browsing system dialog. When the user chooses a file and submits the
form, the browser encodes the file contents for inclusion into the resulting post request.
At that point, the web server receives the request and invokes your script to process it.
The specifics vary for particular APIs, but file uploads generally work like this:
• The file will already have been uploaded and stored in a temporary directory by the
time your upload-handling script begins executing. All your script has to do is read
it. The temporary file is available to your script either as an open file descriptor or
the temporary filename, or perhaps both. The file size can be obtained through the
Search WWH ::




Custom Search