coldfusioncffile

How to store an image file after uploading the image file in ColdFusion


I am fairly new to Coldfusion and I am having a hard time to figure out how to allow users to upload images in my form

Currently, I was able to find the following code that will upload the image in Coldfusion:

<cfparam name="form.fileUpload" default="">
​
<cfif len(trim(form.fileUpload))>
  <cffile action="upload"
     fileField="fileUpload"
     destination="C:\docs">
  <p>Thankyou, your file has been uploaded.</p>
</cfif>
​
<form enctype="multipart/form-data" method="post">
  <input type="file" name="fileUpload" /><br />
  <input type="submit" value="Upload File" />
</form>

Although it gives me an idea on how to approach my issue, I still not sure on the following:

Instead of the destination="C:\docs" storing the file at a drive, I would like to be able to upload the uploaded image to an email. The reason being is the once the user finishes and submits the form, an email will be sent out to the user who submitted the request and the user who will be assigned in creating the card.

How can I achieve this? Any suggestions and examples would be greatly appreciated


Solution

  • Use CFMAILPARAM with remove="yes". You can also show the filename in the email. Full example:

    <cfmail
        to="the@recipient.com"
        subject="#application.companyName# Contact Submission"
        type="html"
        from="#form.email#">
    
        <!--- WAS A FILE UPLOADED? --->
        <cfif isDefined("form.attachment") and form.attachment neq ''>
            <!--- SAVE THE FILE --->
            <cffile action="upload" fileField="attachment" destination="#expandPath('./')#" nameConflict="Overwrite">
            <!--- ATTACH TO EMAIL, THEN DELETE IT --->
            <cfmailparam
                disposition = "attachment"
                file = "#expandPath('./' & cffile.serverfile)#"
                remove = 'yes'>
            <!--- MAKE THE FILE NAME A FORM FIELD --->
            <cfset form.attachment = cffile.serverfile>
        </cfif>
    
        <html>
        <body>
            <cfset form.URL = cgi.http_referrer>
            <table border="1" cellspacing="0" cellpadding="3">
                <tr>
                    <th>Field</th>
                    <th>Value</th>
                </tr>
                <cfloop list="#form.fieldnames#" index="f">
                    <tr>
                        <td nowrap="nowrap" valign="top">#replace(f, '_', ' ', 'all')#</td>
                        <td>#form[f]#</td>
                    </tr>
                </cfloop>
            </table>
        </body>
        </html>
    </cfmail>