Database Reference
In-Depth Information
sysread ( $fh , $data , $size ) == $size
or die "Failed to read entire file $file_name: $!\n" ;
$fh -> close ();
# Save image file in filesystem under $image_dir. (Overwrite file
# if an old version exists.)
my $image_path = $image_dir . $path_sep . $image_name ;
sysopen ( $fh , $image_path , O_WRONLY | O_CREAT )
or die "Cannot open $image_path: $!\n" ;
binmode ( $fh ); # helpful for binary data
syswrite ( $fh , $data , $size ) == $size
or die "Failed to write entire image file $image_path: $!\n" ;
$fh -> close ();
# Save image in database table. (Use REPLACE to kick out any old image
# that has the same name.)
my $dbh = Cookbook:: connect ();
$dbh -> do ( "REPLACE INTO image (name,type,data) VALUES(?,?,?)" ,
undef ,
$image_name , $mime_type , $data );
$dbh -> disconnect ();
If you invoke the script with no arguments, it displays a short help message. Otherwise,
it requires two arguments that specify the name of the image file and the MIME type of
the image. By default, the file's basename (final component) is also used as the name of
the image stored in the database and in the image directory. To use a different name,
provide it using an optional third argument.
The script is fairly straightforward. It implements the following procedure:
1. Check that the proper number of arguments was given and initialize some variables
from them.
2. Make sure the image directory exists. If it does not, the script cannot continue.
3. Open and read the contents of the image file.
4. Store the image as a file in the image directory.
5. Store a row containing identifying information and the image data in the image
table.
store_image.pl uses REPLACE rather than INSERT so that you can replace an old image
with a new version having the same name simply by loading the new one. The statement
specifies no id column value; id is an AUTO_INCREMENT column, so MySQL assigns a
unique sequence number automatically. If you replace an image by loading a new one
with the same name as an existing image, the REPLACE statement generates a new id
value. To keep the old value, use INSERT ON DUPLICATE KEY UPDATE instead (see
Search WWH ::




Custom Search