Save file to MySQL using Coldfusion

I am trying to save a file (pdf or image) uploaded from a form to a MySQL database using Coldfusion. I am saving a file as binary data in a database that has a column set up as BLOB, but cannot write the file back to the screen. What is the correct way to save the file to the database and then restore the file in Coldfusion? Note. The client wants the files stored in the database, not the filesystem.

Saving a File in Database Code

<cffile action="upload" filefield="form.file_upload" destination="#fileDirectory#" result="file_result" nameconflict="makeunique">

<cfif #file_result.fileWasSaved# IS 'Yes'>
   <cfset title = Evaluate('form.file_title')>

   <cffile action="readbinary" file="#fileDirectory#/#file_result.serverFile#" variable="file_binary_data">

   <cfquery name="insertFile" datasource="#request.app.datasource#">
    INSERT INTO (table) (form_id, file_name, file_info)
    VALUES ('#form_id#', <cfqueryparam value="#title#" cfsqltype="CF_SQL_VARCHAR">, <cfqueryparam value="#file_binary_data#" cfsqltype="CF_SQL_BLOB">)
   </cfquery>

      

Writing a file to the screen

<cfheader name="content-length" value="#ArrayLen( getFile.file_info )#" />
<cfheader name="content-disposition" value="inline; filename=#getFile.file_name#.gif" />
<cfcontent type="image/*" variable="#getFile.file_info#">

      

+2


source to share


2 answers


First, make sure you have enabled BLOBs in your Advanced DB Connection settings in Administrator, or that the buffer is large enough to take care of the images.



Secondly, I'll try to try generating just an image instead of writing it on the page to see what the output actually is.

+5


source


I would recommend storing the file on the file system and storing the filename in the database. The database is optimized for storing and retrieving fixed width values; storing huge files there is inefficient.



+1


source







All Articles