Uploading Multiple Files - coldfusion

I have a form where users are to upload at least three documents and up to seven. In its current state, I have all the error checking and validation functioning. What I want to happen is for the visitor's forms to get renamed a specified name once they are uploaded and placed into a specified directory. My code is here: http://pastebin.com/V5ThWe7M
I believe the issue occurs around line 456. I believe I need to have the file name stored in a variable then use the variable to process the renaming function. The first file gets uploaded but not the second as they are assigned the same names. I'm trying to figure out how to use the variables that store the individual file names and then use that variable to rename the file. I'd like to have another set of eyes check it out for me and point me in the right direction.
Thank you

As already mentioned, the CFFILE structure is overwritten each time you upload. So any values you wish to preserve, you must save to another variable. But since you are already saving the full file names to a variable, you could easily extract their extensions using list functions. For example:
<cfset nomExt = listLast(clientNominationLetter, ".")>
A few other observations
Consider a more unique naming scheme for your folders than "/firstName_lastName/". Otherwise, you may end up overwriting someone's files if you receive multiple submissions under the same name, like two different "John Smith's".
The cffile values are separated into two categories: cffile.serverXX and cffile.clientXX (ie user system). They are not interchangeable. So be sure you are using the correct variables and be consistent.
FILE is deprecated. Use CFFILE or the result attribute instead.

EDIT: Adding some new code into the mix... :)
Here's some functions, just slap these in the top of your page...
<cffunction name="uploadFile">
<cfargument name="formField" hint="Form field name that holds the file to be uploaded" required="yes">
<cfargument name="renameTo" hint="What to rename the file, ex: 01_nominationLetter" required="yes">
<cfargument name="uploadErrorMessage" required="no" default="Error uploading file"/>
<cfargument name="allowedExtensions" required="no" default="doc,docx,pdf,txt,rt">
<cfargument name="extensionErrorMessage" required="no" default="Only doc, docx, pdf, txt, and rtf file formats are accepted">
<cfset var dir = expandPath("./nominationUploads/#trim(form.fname)#_#trim(form.lname)#/")>
<cfparam name="request.filesUploaded" default="#arrayNew(1)#">
<cftry>
<cffile action="upload" filefield="#arguments.formField#" nameconflict="makeunique" destination="#dir#">
<cfcatch type="any"><cfset ArrayAppend(arrErrors, arguments.uploadErrorMessage )></cfcatch>
</cftry>
<cfif not listFindNoCase(arguments.allowedExtensions, cffile.ServerFileExt)>
<cfset ArrayAppend(arrErrors, arguments.extensionErrorMessage )>
</cfif>
<cffile action="rename" file="#dir##cffile.serverFile#" destination="#dir##renameTo#.#cffile.ServerFileExt#">
<cfset ArrayAppend(request.filesUploaded, dir & arguments.renameTo & "." & cffile.ServerFileExt )>
</cffunction>
<cffunction name="removeFilesOnError">
<cfloop from="1" to="#arrayLen(request.filesUploaded)#" index="i">
<cftry><cffile action="delete" file="#request.filesUploaded[i]#"/><cfcatch type="any"></cfcatch></cftry>
</cfloop>
</cffunction>
Then in your existing validation script, get rid of all the file stuff, instead you'll only need to use those functions above, something like this :
<cfset uploadFile('myFileField', 'renameToThis' )>
<cfset uploadFile('myFileField2', 'renameToThat' , 'My custom upload error!')>
<cfset uploadFile('anotherFile', 'differentName', 'Another custom upload msg!', 'doc,docx', 'This one only lets you upload word docs!')>
<cfif arrayLen( arrErrors ) >
<cfset removeFilesOnError()>
</cfif>
I don't have time to test the above, but I believe it to be frighteningly close. If you encounter an issue, let me know and I'll help you debug it out. :)

Related

Excluding items from a list in coldfusion by type

Is there a way to exclude certain items by filetype in a list in Coldfusion?
Background: I just integrated a compression tool into an existing application and ran into the problem of the person's prior code would automatically grab the file from the upload destination on the server and push it to the Network Attached Storage. The aim now is to stop their NAS migration code from moving all files to the NAS, only those which are not PDF's. What I want to do is loop through their variable that stores the names of the files uploaded, and exclude the pdf's from the list then pass the list onto the NAS code, so all non pdf's are moved and all pdf's uploaded remain on the server. Working with their code is a challenge as no one commented or documented anything and I've been trying several approaches.
<cffile action="upload" destination= "c:\uploads\" result="myfiles" nameconflict="makeunique" >
<cfset fileSys = CreateObject('component','cfc.FileManagement')>
<cfif Len(get.realec_transactionid)>
<cfset internalOnly=1 >
</cfif>
**This line below is what I want to loop through and exclude file names
with pdf extensions **
<cfset uploadedfilenames='#myfiles.clientFile#' >
<CFSET a_insert_time = #TimeFormat(Now(), "HH:mm:ss")#>
<CFSET a_insert_date = #DateFormat(Now(), "mm-dd-yyyy")#>
**This line calls their method from another cfc that has all the file
migration methods.**
<cfset new_file_name = #fileSys.MoveFromUploads(uploadedfilenames)#>
**Once it moves the file to the NAS, it inserts the file info into the
DB table here**
<cfquery name="addFile" datasource="#request.dsn#">
INSERT INTO upload_many (title_id, fileDate, filetime, fileupload)
VALUES('#get.title_id#', '#dateTimeStamp#', '#a_insert_time#', '#new_file_name#')
</cfquery>
<cfelse>
<cffile action="upload" destination= #ExpandPath("./uploaded_files/zip.txt")# nameconflict="overwrite" >
</cfif>
Update 6/18
Trying the recommended code helps with the issue of sorting out filetypes when tested outside of the application, but anytime its integrated into the application to operate on the variable uploadedfilenames the rest of the application fails and the multi-file upload module just throws a status 500 error and no errors are reported in the CF logs. I've found that simply trying to run a cfloop on another variable not related to anything in the code still causes it to error.
As per my understanding, you want to filter-out file names with a specific file type/extension (ex: pdf) from the main list uploadedfilenames. This is one of the easiest ways:
<cfset lFileNames = "C:\myfiles\proj\icon-img-12.png,C:\myfiles\proj\sample-file.ppt,C:\myfiles\proj\fin-doc1.docx,C:\myfiles\proj\fin-doc2.pdf,C:\myfiles\proj\invoice-temp.docx,C:\myfiles\proj\invoice-final.pdf" />
<cfset lResultList = "" />
<cfset fileExtToExclude = "pdf" />
<cfloop list="#lFileNames#" index="fileItem" delimiters=",">
<cfif ListLast(ListLast(fileItem,'\'),'.') NEQ fileExtToExclude>
<cfset lResultList = ListAppend(lResultList,"#fileItem#") />
</cfif>
</cfloop>
Using only List Function provided by ColdFusion this is easily done, you can test and try the code here. I would recommend you to wrap this code around a function for easy handling. Another way to do it would be to use some complex regular expression on the list (if you're looking for a more general solution, outside the context of ColdFusion).
Now, applying the solution to your problem:
<cfset uploadedfilenames='#myfiles.clientFile#' >
<cfset lResultList = "" />
<cfset fileExtToExclude = "pdf" />
<cfloop list="#uploadedfilenames#" index="fileItem" delimiters=",">
<cfif ListLast(ListLast(fileItem,'\'),'.') NEQ fileExtToExclude>
<cfset lResultList = ListAppend(lResultList,fileItem) />
</cfif>
</cfloop>
<cfset uploadedfilenames = lResultList />
<!--- rest of your code continues --->
The result list lResultList is copied to the original variable uploadedfilenames.
I hope I'm not misunderstanding the question, but why don't you just wrap all of that in an if-statement that reads the full file name? Whether the files are coming one by one or through a delimited list, it should be easy to work around.
<cfif !listContains(ListName, '.pdf')>
OR
<cfif FileName does not contain '.pdf'>
then
all the code you posted

ColdFusion cfautosuggestvalue content is blank, even though a good array is returned from the cfc

I'm working with ColdFusion Server version 8,0,0,176276.
I'm trying to add an autosuggested form field, with asynchronous population through a cfc. I'm using http://www.forta.com/blog/index.cfm/2007/5/31/coldfusion-ajax-tutorial-1-autosuggest for inspiration and syntax.
The autosuggest field works fine if I use a static query (as in Forta's first example). The cfc is successfully returning an array when not used in the form field.
But when I use the cfc for autosuggest, there are no suggestions provided.
I can't see the contents of the input field with "view source," but if I do "inspect element" on the field in Chrome, I can see a div with class="yui-ac-bd" and a ul under it. The list items in the ul are empty when using the cfc, whereas when I use a static query, the list items contain the array members.
Here's the code on my page:
<cfform>
<cfinput type="text" name="JobP"
autosuggest="cfc:autosuggest.AutoSuggest({cfautosuggestvalue})">
</cfform>
And here's autosuggest.cfc:
<cfcomponent output="false" >
<cffunction name="AutoSuggest" access="remote" returntype="array">
<cfargument name="ObjectType" required="false" default="JOBP">
<cfset var result=ArrayNew(1)>
<cfquery name="Objects" datasource="UC4MP">
SELECT oh_name
FROM uc4.oh
WHERE oh_otype = '#ObjectType#'
AND oh_deleteflag = 0
AND oh_lastdate > sysdate - 90
AND oh_client = 1000
and oh_name like 'A%'
ORDER BY oh_name
</cfquery>
<cfloop query="Objects">
<cfset ArrayAppend(result,oh_name)>
</cfloop>
<cfreturn result>
If I put the following code on my page, it outputs the array with the desired contents:
<cfinvoke component="autosuggest" method="AutoSuggest" returnVariable="result">
cfdump var="#result#">
I don't use jQuery yet; most of my Google results for CF autosuggest have involved jQuery and I haven't been able to wade through them for relevance to my problem. Just in case that was going to be your suggestion.
Thank you all for your advice! I had not known there was a separate ajax debugger, the output of which immediately made the problem clear:
info:http: Invoking CFC: /rd/autosuggest.cfc , function: AutoSuggest ,
arguments: {"ObjectType":"A"}
My cfc arguments didn't include the autosuggest itself, so the string passed to the input field was being interpreted as "ObjectType" (the first argument) and used in the query. Since there are no records where oh_otype = 'A', the result was always empty.
I updated my cfc's arguments to
<cfargument name="ObjectType" required="yes" default="JOBP">
<cfargument name="autosuggest" required="yes">
and the invocation to
<cfinput type="text" name="JobP"
autosuggest="cfc:autosuggest.AutoSuggest('JOBP',{cfautosuggestvalue})">
...works perfectly now.
If i remember correctly when I did this some years ago, I had to create a virtual directory in Apacahe and set permisions using the following directives. You can apply the same to IIS if you are working in that environment. That should get it going for you.
Alias /CFIDE "/opt/coldfusion9/wwwroot/CFIDE"
<Directory "/opt/coldfusion9/wwwroot/CFIDE">
allow from all
Options FollowSymLinks
Since then I have been using the typehead javascript from bootstrap 2. Much cleaner and easier to style. You can still use your cfc to call the data and I am including the code to clean it up for typehead.
<cfinvoke component="autosuggest" method="AutoSuggest" returnVariable="result">
<cfset mylist = ArrayToList(result, ",")>
<cfset mylist=ValueList(ShowKey.keyword)>
<cfset mylist = jSStringFormat(#mylist#)>
<input name="keyword" id="keyword" type="text" data-provide="typeahead" data-items="10" data-source='["<cfoutput>#replace(mylist,',','","','ALL')#</cfoutput>"]'/>

Reading a CSV or Pipe delimited file

I am trying to read a csv file that is using a | delimiter instead of ,.
I am using
<cffunction name="loadCSVfile" access="public" returntype="string">
<cfargument name="filename" required="yes" default="">
<cffile action="read" file="#filename#" variable="csvData">
<cfreturn csvData>
</cffunction>
which works fine with files that are , delimiter but does not work with |. Is there anything else that I need to do for this function to work?
This is how I'm calling the function:
<cfscript>
csvloaderCFC = CreateObject("component","AlscCSVloader");
</cfscript>
<cfset csvfilename = DataDirectory&q_DataDirectory.name>
<!--- backup CSV file ---->
<cffile action= "copy" source = "#csvfilename#"
destination = "#DataDirectorybackup#">
<!--- Load CSV data ---->
<cfscript>
csvData = csvloaderCFC.loadCSVfile(csvfilename);
</cfscript>
<cfdump var="#csvData#">
The cfdump in the end it doesn't show at all
Pipe-delimitted sample
Location|patient_ID|First Name|Last Name|
111|468454|Eric |Gallegos |
111|468457|kelsey|anderson|
10|468459|Rivenda|Kaur|
Comma-delimitted sample
Location,patient_ID,First Name,Last Name,
111,468454,Eric ,Gallegos ,
111,468457,kelsey,anderson,
10,468459,Rivenda,Kaur,
There is quite a bit more you have do do than just a CFFile call to get a CSV as a struct of some kind. CFFile foes not do this on it's own. (although strangely CFHttp does) Honestly your best bet may be to be to use a Java library. There are several available from Apache: http://commons.apache.org/csv/
These should give you back something fairly easy to deal with.
If you want a "pure" coldfusion CSV option you can look at this blog post for a specific impl:
http://www.bennadel.com/blog/483-Parsing-CSV-Data-Using-ColdFusion.htm
basically you need to read the entire content and then parse it.

ColdFusion = OnRequest Error

Looking through the logs, we're getting hundreds of the following
"Error","jrpp-185","08/21/12","10:05:43","PATH","www.domain.com
Agent:Mozilla/4.0 (compatible; Synapse)
Error: An exception occurred when invoking a event handler method from Application.cfc.
The method name is: onRequest.
They seem to be mostly search bots. The on place on APplication.cfc that I can see reference to the function is below
<cffunction name="onRequest" returnType="void">
<cfargument name="targetPage" type="String" required=true/>
<cfsetting enablecfoutputonly="yes" requesttimeout="20">
<cfparam name="url.refresh" default="0">
<cfset request.strMember = Duplicate(session.strMember)/>
<cfset request.tNow = GetTickCount()>
<cfif url.refresh EQ 0>
<cfset request.iCacheHr = 12/>
<cfelse>
<cfset request.iCacheHr = 0/>
</cfif>
<cflogin>
<cfif IsDefined("session.strMember.sRoles")>
<cfloginuser name="#session.strMember.sFirstName##session.strMember.sLastName#"
password="12345"
roles="#session.strMember.sRoles#"/>
</cfif>
</cflogin>
<cfinclude template="core/incl/SessionLogger.cfm">
<cfinclude template="core/incl/LinkTranslator.cfm">
<cfinclude template="core/incl/udf.cfm">
<cfinclude template="urlcheck.cfm"/>
<cfinclude template="#Arguments.targetPage#">
</cffunction>
From that, can anyone please advise on what's wrong and how to fix it? I'm fairly new to CF and this is making me pull out what little hair I have left
1) You use two different coding styles
<cfparam name="url.refresh" default="0">
<cfset request.strMember = Duplicate(session.strMember)/>
Invalid/left open XML tags in first line and valid (closed) XML tags in the second line.
Try to stick to one (preferably the last one).
2) You are using old way of checking variable being defined
IsDefined("session.strMember.sRoles")
read about newer (and better and faster)
StructKeyExists(session.strMember, "sRoles")
3) Most likely your code is calling
<cfloginuser ... >
at every page request
4) Make sure that paths for all includes are correct and they themselves don't have any errors.
Simplify your method until you stop getting an error and then investigate what exactly is causing it
Are the bots hitting a page that doesn't exist?
Maybe try changing the last line to:
<cfif fileExists(expandPath(Arguments.targetPage))>
<cfinclude template="#Arguments.targetPage#">
<cfelse>
<cfabort>
</cfif>
Maybe you could detect if they are a bot and server them something else? depends on how search friendly you want your site to be:
http://www.bennadel.com/blog/1083-ColdFusion-Session-Management-And-Spiders-Bots.htm

Coldfusion: splitting a tag across onRequestStart() and onRequestEnd() in Application.cfc

I'm trying to see if there is a way to split a CFSAVECONTENT tag across the onRequestStart() and onRequestEnd() functions in Application.cfc to save the generated HTML of any .cfm page in the application to a variable.
Adding <cfsavecontent variable="html"> to onRequestStart() and adding </cfsavecontent> to onRequestEnd() isn't allowed since the tag must be closed in the function.
Is this even possible to do? I'm trying to avoid hard coding the CFSAVECONTENT this into every .cfm page of the site.
Thanks!
Alex,
You could do something like this in OnRequest (untested, but should work).
<cffunction name="onRequest" returnType="void">
<cfargument name="thePage" type="string" required="true">
<cfsavecontent variable="html">
<cfinclude template="#arguments.thePage#">
</cfsavecontent>
<!--- do whatever you want with the html variable here (for example, output it) --->
<cfoutput>#html#</cfoutput>
</cffunction>
I realize this has an accepted answer already, but another way to accomplish this without using cfinclude would be to use the getPageContext() object in onRequestEnd() to nab the generated content:
<cffunction name="onRequestEnd" output="yes">
<cfargument type="string" name="targetPage" required="true" />
<cfset var html = getPageContext().getOut().getString() />
<!--- Manipulate the html variable. --->
<cfoutput>#html#</cfoutput><cfabort />
</cffunction>
The <cfabort /> is important here because if you don't abort the request, the CF engine will output the generated content again and it will end up sending two copies of the output along.
I've used this method to apply site-wide changes to content on sites in a crunch where finding every instance of the original content wasn't practical or timely enough. It can also be used to send the generated content out to a translation service if needed before being returned to the end-user.