If your MySQL database is running on a remote server then it can be quite a job to load a binary file (such as a jpg, movie or zip file) directly into the database when you have no file access to that server.
This bash script gets round the problem by converting the file to HEX and uploading it to the database:
#!/bin/bash
#Uploads a file (parm 2) to a database with id=parm 1
#INITIALISATION=====
#the id in the SQL table to update
ID=$1
#filename of file to upload
SOURCE=$2
#Some internal initialisation
TMPFILE="$SOURCE.hex"
SQL="/PATH_to_MYSQL/mysql -uUSERNAME -pPASSWORD DATABASENAME -BNe"
# PROCESS===========
#Let the user know whats going on
echo "Uploading '${SOURCE}' to database with 'id=${ID}'"
#Convert the file to a hexed version
/usr/bin/hexdump -ve '1/1 "%02X"' ${HEXPARMS} ${SOURCE} > ${TMPFILE}
#Upload into the database, unhexing as we go
$SQL "update files set data=unhex('`cat ${TMPFILE}`') where id='$1'"
# CLEANUP============
#Tidy up
rm -f ${TMPFILE}
echo "Upload completed."
Category: SQL
|

