• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1121
  • Last Modified:

ReReplace to remove spaces on upload?

I have a page working just fine to upload image files, and do a bunch of 'other stuff' with the image too.

But for some reason I just can't get my rereplace function working like I want,
to replace all spaces in the filename with a hyphen.

I have the syntax right, but can't get it working with my existing page
within the flow of this somewhat twisted and convoluted file upload routine.
Can anybody take a look at my entire page code, and suggest a fix?


///////////////   relevant section of page //////////////////

  <!--- Determine the name of the real file and rename the new one. --->
  <cfset realFileName= Left(GetToken(form.file, 1, "."), Len(GetToken(form.file, 1, ".")) -1) & "." &  GetToken(form.file, 2,
".") />

  <cffile action="rename" destination="#originalFilePath#/#REReplace(realFileName,"[[:space:]]","-","ALL")#"
source="#originalFilePath#/#form.file#">

<!--- added 20060705 ME :: Replace spaces with hyphen --->
<cfset realFileName = "#Rereplace(realFileName,"[[:space:]]","-","ALL")#">


  <!--- Create a name for the image. --->
  <cfset imageUploaded = originalFilePath & "/" & realFileName />
  <cfset imageThumb = ThumbFilePath & "/" & realFileName />
  <cfset imageFull = FullFilePath & "/" & realFileName />




////////////////////////  my entire  page code ////////////////



<cfparam name="url.message" type="string" default="" />
<cfparam name="url.picturename" type="string" default="" />
<cfparam name="url.uploadedfile" type="string" default="" />
<cfparam name="variables.imagespath" type="string" default="c:/domains/furryfriendshaven.com/wwwroot/mreCFcms/admin/images/" />
<cfparam name="variables.imagesurl" type="string" default="http://furryfriendshaven.com/mreCFcms/admin/images/" />
<cfparam name="variables.maxthumbh" type="string" default="120" />
<cfparam name="variables.maxthumbw" type="string" default="120" />
<cfparam name="variables.maxfullh" type="string" default="240" />
<cfparam name="variables.maxfullw" type="string" default="240" />

<!--- Create paths for images --->
<cfset originalFilePath =  Trim(variables.imagespath) & "original" />
<cfset fullFilePath =  Trim(variables.imagespath) & "full" />
<cfset thumbFilePath =  Trim(variables.imagespath) & "thumb" />

<!--- size view in display --->
<cfif isdefined('url.sizeview') >
<cfif #url.sizeview# eq 1>
<cfset sizeview = 1>
<cfelse>
<cfset sizeview = 2>
</cfif>
<cfelse>
<cfset sizeview = 1>
</cfif>

<!---if using associated RECORD--->
<cfif isdefined("url.recordID")>
<cfset recordID = #url.recordID#>
<cfquery datasource="#application.dsn#" name="getRecord">
select * from Records
where recordID = #url.recordID#
</cfquery>
<cfoutput query="getRecord">
<cfset recordTitle = #recordTitle#>
</cfoutput>
</cfif>
<cfif isdefined("form.recordID")>
<cfset formID = #form.recordID#>
<cfquery datasource="#application.dsn#" name="getRecord">
select * from Records
where recordID = #form.recordID#
</cfquery>
</cfif>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<cfinclude template="checkin.cfm">
<cfparam name="url.method" type="string" default="upload" /><head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title><cfoutput>#SiteName# :: #recordLabel#</cfoutput> Administration</title>
<link href="css/adminCss.css" rel="stylesheet" type="text/css" media="screen">
<cfinclude template="includes/includePopupCode.cfm">
</head>
<body>
<div id="wrapper">
<cfinclude template="adminNav.cfm">
<div id="admincol">
 <h2><cfoutput>#SiteName# :: #recordLabel#</cfoutput> Administration </h2>
<table class="admintable">
<tr>
<td colspan="3">
<h1>Upload Image</h1>
</td>
</tr>
<tr>
<td colspan="3">
<cfswitch expression="#url.method#">

 <!--- handle_conflict    - Presents users with a choice about how to handle file conflicts. --->
 <cfcase value="handle_conflict">
<cfset recordID = "#url.recordID#">
<cfoutput>
   <form action="#cgi.script_name#?method=handle_conflict_process" method="post" enctype="multipart/form-data">
    <fieldset>
   <!--- <legend>Conflict</legend>--->
    <p class="error">A file with that name already exists. Would you like to overwrite it?</p>
<input name="recordID" type="hidden" value="#recordID#">
    <input name="file" type="hidden" value="#url.file#" />
    <input name="overwrite" type="submit" value="Yes" class="formbutton">&nbsp;&nbsp;&nbsp;&nbsp;
    <input name="overwrite" type="submit" value="No" class="formbutton"><br />
    </fieldset>
   </form>
  </cfoutput>
 </cfcase>

 <!--- handle_conflict_process - Handles the form input from the handle conflict page. --->
 <cfcase value="handle_conflict_process">
  <cfif not isDefined("form.overwrite")>
   <cflocation url="#cgi.script_name#" addtoken="no" />
  </cfif>

  <!--- If we're not overwriting, delete the new original. --->
  <cfif not form.overwrite>
   <cffile action="delete" file="#originalFilePath#/#form.file#" />
   <cflocation url="#cgi.script_name#" addtoken="no">
  </cfif>

  <!--- Determine the name of the real file and rename the new one. --->
  <cfset realFileName= Left(GetToken(form.file, 1, "."), Len(GetToken(form.file, 1, ".")) -1) & "." &  GetToken(form.file, 2,
".") />

  <cffile action="rename" destination="#originalFilePath#/#REReplace(realFileName,"[[:space:]]","-","ALL")#"
source="#originalFilePath#/#form.file#">

<!--- added 20060705 ME :: Replace spaces with hyphen --->
<cfset realFileName = "#REReplace(realFileName,"[[:space:]]","-","ALL")#">


  <!--- Create a name for the image. --->
  <cfset imageUploaded = originalFilePath & "/" & realFileName />
  <cfset imageThumb = ThumbFilePath & "/" & realFileName />
  <cfset imageFull = FullFilePath & "/" & realFileName />

  <!--- Try and Catch files that are not really images, or are malformed. --->
  <cftry>

   <!--- Format the Thumbnail--->
   <cfinvoke component="picture" method="format">
    <cfinvokeargument name="imageToRead" value="#imageUploaded#" />
    <cfinvokeargument name="imageToWrite" value="#imageThumb#" />
    <cfinvokeargument name="idealheight" value="#variables.maxthumbh#" />
    <cfinvokeargument name="idealwidth" value="#variables.maxthumbw#" />
   </cfinvoke>

   <!--- Format the "fullSized" image--->
   <cfinvoke component="picture" method="format">
    <cfinvokeargument name="imageToRead" value="#imageUploaded#" />
    <cfinvokeargument name="imageToWrite" value="#imageFull#" />
    <cfinvokeargument name="idealheight" value="#variables.maxfullh#" />
    <cfinvokeargument name="idealwidth" value="#variables.maxfullw#" />
   </cfinvoke>

   <cfcatch type="any">
    <cfif FindNoCase("Failed to read image dimensions", cfcatch.message)>
     <cfset message =  "notanimage" />
     <cfif fileExists(imageUploaded)>
      <cffile action="delete" file="#imageUploaded#" />
     </cfif>
     <cfif fileExists(imagePreview)>
      <cftry>
       <cffile action="delete" file="#imagePreview#" />
       <cfcatch type="any" />
      </cftry>
     </cfif>

     <cflocation url="#cgi.script_name#?message=#message#" addtoken="no">
    <cfelse>
     <cfrethrow />
    </cfif>
   </cfcatch>
  </cftry>

  <cfset message =  "uploaded" />
<cfif isdefined ("form.recordID")>
  <cflocation url="#cgi.script_name#?message=#message#&picturename=#realFileName#&recordid=#recordID#" addtoken="no" />
<cfelse>
  <cflocation url="#cgi.script_name#?message=#message#&picturename=#realFileName#" addtoken="no" />
</cfif>
 </cfcase>

 <!--- upload_process   - Process the image from the upload form --->
 <cfcase value="upload_process">
  <cfif isdefined ("form.recordID")>
<cfset recordID="#form.recordID#">
</cfif>
  <!--- IF they didn't upload anything... send them back. --->
  <cfif not len(form.picture)>
   <cfset message =  "imageinvalid" />
   <cflocation url="#cgi.script_name#?message=#message#" addtoken="no" />
  </cfif>

  <!--- Get the file from the user. --->
  <cffile action="upload" destination="#originalFilePath#" filefield="picture" nameconflict="overwrite" />

  <!--- This should catch name conflicts.  --->
  <!--- This may however lead to false positives. Unfortunately the cfcatch structure isn't well defined for this error.  --->
  <cfif cffile.filewasrenamed>
   <cfset message =  "imagenotunique" />
   <cfif isdefined('recordID')><cflocation
url="#cgi.script_name#?method=handle_conflict&file=#cffile.attemptedserverfile#&recordID=#recordID#" addtoken="no" />
  </cfif>
</cfif>

  <!--- tpryan 12:50pm 5/29/2006 --->
  <!--- tpryan 12:09pm 5/30/2006 --->
  <!--- Block that fixes pdf submissions not being caught. --->
  <!--- Note that the variable TemporaryImageName is what's causing the problem.  --->
  <cfif Not ListFindNoCase("png,jpg,gif", cffile.serverfileext)>
   <cfset message =  "imageinvalid" />
   <cffile action="delete" file="#originalFilePath#/#cffile.attemptedserverfile#" />
   <cflocation url="#cgi.script_name#?message=#message#" addtoken="no">
  </cfif>
  <!--- End - Block that fixes pdf submissions not being caught. --->

   <!--- IF they didn't upload a file... send them back. --->
  <!---<cfif Not ListFindNoCase("png,jpg,gif", cffile.serverfileext)>
   <cfset message =  "imageinvalid" />
   <cffile action="delete" file="#temporaryImageName#" />
   <cflocation url="#cgi.script_name#?message=#message#" addtoken="no">
  </cfif> --->

  <!--- Create a name for the image. --->

  <cfset imageUploaded = originalFilePath & "/" & cffile.serverFile />
  <cfset imageThumb = ThumbFilePath & "/" & cffile.serverFile />
  <cfset imageFull = FullFilePath & "/" & cffile.serverFile />

  <!--- Try and Catch files that are not really images, or are malformed. --->
  <cftry>



   <!--- Format the Thumbnail--->
   <cfinvoke component="picture" method="format">
    <cfinvokeargument name="imageToRead" value="#imageUploaded#" />
    <cfinvokeargument name="imageToWrite" value="#imageThumb#" />
    <cfinvokeargument name="idealheight" value="#variables.maxthumbh#" />
    <cfinvokeargument name="idealwidth" value="#variables.maxthumbw#" />
   </cfinvoke>

   <!--- Format the "fullSized" image--->
   <cfinvoke component="picture" method="format">
    <cfinvokeargument name="imageToRead" value="#imageUploaded#" />
    <cfinvokeargument name="imageToWrite" value="#imageFull#" />
    <cfinvokeargument name="idealheight" value="#variables.maxfullh#" />
    <cfinvokeargument name="idealwidth" value="#variables.maxfullw#" />
   </cfinvoke>

   <cfcatch type="any">
    <cfif FindNoCase("Failed to read image dimensions", cfcatch.message)>
     <cfset message =  "notanimage" />
     <cfif fileExists(imageUploaded)>
      <cffile action="delete" file="#imageUploaded#" />
     </cfif>
     <cfif fileExists(imagePreview)>
      <cftry>
       <cffile action="delete" file="#imagePreview#" />
       <cfcatch type="any" />
      </cftry>
     </cfif>

     <cflocation url="#cgi.script_name#?message=#message#" addtoken="no">
    <cfelse>
     <cfrethrow />
    </cfif>
   </cfcatch>
  </cftry>

  <cfset message =  "uploaded" />
<cfif isdefined ("form.recordID")>
  <cflocation url="#cgi.script_name#?message=#message#&picturename=#cffile.serverFile#&recordid=#recordID#" addtoken="no" />
<cfelse>
  <cflocation url="#cgi.script_name#?message=#message#&picturename=#cffile.serverFile#" addtoken="no" />
</cfif>
 </cfcase>
<!--- end upload handling--->


 <!--- upload (default)   - Display a form to take the input from the user --->
 <cfdefaultcase>
  <!--- Process Message from form submission --->
  <cfswitch expression="#url.message#">
   <cfcase value="uploaded">
    <cfset userMessage = "Your file has been uploaded." />
    <cfset userMessageType = "notice" />
   </cfcase>
   <cfcase value="imagenotunique">
    <cfset userMessage = "Are you sure you want to overwrite this file?" />
    <cfset userMessageType = "notice" />
   </cfcase>
   <cfcase value="imageinvalid">
    <cfset userMessage = "Please upload a valid picture file (jpg, gif, png.)" />
    <cfset userMessageType = "notice" />
   </cfcase>
   <cfcase value="notanimage">
    <cfset userMessage = "Image unable to be processed. (Could be corrupt or using unknown compression.)" />
    <cfset userMessageType = "notice" />
   </cfcase>
   <cfdefaultcase>
    <cfset userMessage = "For best results, use an image smaller than 1mb" />
    <cfset userMessageType = "default" />
   </cfdefaultcase>
  </cfswitch>

  <!--- Present the form to display to the user. --->
  <cfoutput>
   <form action="#cgi.script_name#?method=upload_process" method="post" enctype="multipart/form-data">

   <cfif isdefined ("url.recordID")>
<input type="hidden" value="#url.recordID#">
</cfif>
    <fieldset>
 <cfif not CompareNoCase(userMessageType, "notice")>
     <p class="error">#userMessage#</p>
    <cfelse>
     <p class="message">#userMessage#</p>
    </cfif>
<!--- IF Photo has been uploaded --->
 <cfif Len(url.picturename)>
<!--- IF using associated record --->
<cfif isdefined ("url.recordID")>
<cfoutput>
<p class="alert" align="center"><a href="recordForm.cfm?recordID=#recordID#&recordPhotoFilename=#url.picturename#">Return to
#recordLabel#:<br>
</a><a
href="recordForm.cfm?recordID=#recordID#&recordPhotoFilename=#url.picturename#"><strong>#getRecord.recordMainText#</strong></a></p>
</cfoutput>
<cfelse>
<p class="alert" align="center"><a href="recordForm.cfm?recordPhotoFilename=#url.picturename#">Proceed to New #recordLabel#
Form</a></p>
</cfif>
<p align="center">&nbsp;</p>
   <p align="center">Filename: #url.picturename#</p>
<p class="smallprint">
<cfif #sizeView# eq 1>
<a href="#cgi.script_name#?#cgi.query_string#&sizeview=2">Full Size</a>
<cfelse>
<a href="javascript:history.back()">Thumbnail</a>
</cfif>
&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:popImage('#imagesurl#original/#url.picturename#','File Preview')">Original
Image</a></p>
    <cfif #sizeView# eq 1>
 <a href="#cgi.script_name#?#cgi.query_string#&sizeview=2"><img src="#variables.imagesurl#thumb/#url.picturename#" /></a>
</cfif>
<cfif #sizeView# eq 2>
<a href="javascript:history.back()"><img src="#variables.imagesurl#full/#url.picturename#" /></a>
</cfif>
<p class="smallprint">&nbsp;</p>
   <cfelse>
<!---if not, show UPLOAD FORM --->
    <p align="center">Upload file:</p>
<cfif isdefined("url.recordID")>
<input name="recordID" type="hidden" value="#recordID#">
</cfif>
    <input name="picture" type="file" class="file" id="picture" size="35" value="#url.uploadedfile#" /> <br />
    <input name="upload" type="submit" value="Upload" class="formbutton"><br />
</cfif>
    </fieldset>
   </form>
  </cfoutput>
 </cfdefaultcase>
</cfswitch>
</td>
      </tr>
</table>
</table>
</div>
</div>
</body>
</html>
<cfabort>



0
MichaelEvangelista
Asked:
MichaelEvangelista
  • 10
  • 6
1 Solution
 
siva350Commented:
Try replacing
<cfset realFileName = "#Rereplace(realFileName,"[[:space:]]","-","ALL")#">

With
<cfset realFileName = "#Rereplace(realFileName," ","-","ALL")#">
0
 
MichaelEvangelistaAuthor Commented:
Thanks but no joy.
THis is so frustrating, I KNOW I had it working on another site, but it no longer works there and I cant get it here either.

Is there any chance at all this has something to do with my host server?
I have been at this one problem for hours and just cannot get it going,
though everything seems just exacly like it should be. aargh!
0
 
usachrisk1983Commented:
Try:

<cfset realFileName = ReReplace(realFileName,"[[:space:]]","-","ALL")>

Also, are you sure it's a space?  I'm not sure that any crazy characters are allowed in file names, and I'm also not sure of your OS, but perhaps it's another character.  If the above doesn't work, do something like this (for debugging):

<cfloop index="i" from="1" to="#Len(realFileName)#">
  <cfoutput>Character #i# is #mid(realFileName,i,1)# (ASCII Code: #asc(mid(realFileName,i,1))#)<br>
</cfloop>
<cfabort>

If your "space" comes out as anything except ASCII Code 32, it's not really a space.
0
Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

 
MichaelEvangelistaAuthor Commented:
sorry, i cant get the output part of that working, where should I be putting it?

this is SOOOO frustrating because I did have the rereplace bit working on another site, now it is not working there or on this new page!!!

is there ANY chance this could be something on the server, some issue with cffile and renaming? aaargh.

0
 
MichaelEvangelistaAuthor Commented:
I am on winXP
0
 
MichaelEvangelistaAuthor Commented:
Ok never mind my Q about the server, just made a test page and it works perfectly.
Not with rereplace, but with a simple name change.

Another Q - I think this site is on CF6 (mx)... would that matter?
0
 
MichaelEvangelistaAuthor Commented:
WAY off...
Ok, sorry. Now I realize my code is not being processed at all.

I changed the whole stinking mess to
<cfset realfilename = "nuts.jpg">
and the file being uploaded was not renamed.

So... this means something *else* is wrong!
aaaargh.

I would gladly purchase a bit of someone's time if I knew they could straighten this up for me.
0
 
usachrisk1983Commented:
<!---- Snip ---->
  <cffile action="upload" destination="#originalFilePath#" filefield="picture" nameconflict="overwrite" />
<!---- Snip ---->

After this, try <cfdump var="#cffile#"><cfabort>

Then you'll be able to see info about the uploaded file (and maybe why it's not uploading, or going to the wrong place?)
0
 
usachrisk1983Commented:
Sorry, take that back, I see it's not an upload problem but a rename problem.
0
 
MichaelEvangelistaAuthor Commented:
I see I have you on both points here... cool

I more or less started over with the upload routine ( aargh... all day )
and now, finally, I see why parts of this are not working.
My files are getting renamed to temporary names, somewhere between the form
and the cffile action.

I am totally lost now.
Why in the world would 'image.jpg' get renamed to something like
'neotmp961.tmp' ?

This relates both to this problem and the other one.
I trimmed the filename out of the form field, and this temp name is what is left!
0
 
MichaelEvangelistaAuthor Commented:
I guess I should restate this question altogether.

:: NEW SUBJECT ::

How can I check a directory of existing files on the server,
to see if it has the same name as the file I am trying to upload with cffile?

In other words, rather than "makeunique" or "overwrite" I want to specify
a <cflocation tag...  ?

That is all I am trying to do at this point, with all the tangle of the form field name, etc.

Any ideas??
0
 
usachrisk1983Commented:
The file is uploaded to the server as a temporary file as part of the form upload.  Although you're telling CFFILE to "Upload", all this is really doing is taking it from that temporary place, and putting it where you specify, with the name you specify.  

ColdFusion knows by your fileField (or Destination since you can specify it there) what the file should be called.

What is the exact end result that you're looking for?
0
 
MichaelEvangelistaAuthor Commented:
Here is the flow of my pages:

File is uploaded, unchanged, to a directory called /original/
Then the file which was placed in the /original/ directory is resized,
and placed into the /full/ directory.
It is then resized again, and a smaller copy placed into the /thumb/ directory.

As it stands, I am taking the 'serverfile' from the initial upload ( to the /original/ folder ),
and checking against the names of the files in the /full/ directory to see if there are any duplicates. If so, there is a prompt for "overwrite y/n" with the option to cancel the resizing and creation of the other 2 images.

Everything is running on greased rails, only problem is that the /original/ version gets overwritten automatically if same name. I want to check the filename for duplicates *before* running that initial <cffile> routine into the /original/ folder. So, I need another way, besides the cffile.serverfile attribute, to get hold of the file name data so I can run the check.

And I thought I had it.. until that .tmp file showed up instead!
0
 
usachrisk1983Commented:
Hmm, what if you did this:  

- User submits file, CFFILE does MAKEUNIQUE, and puts it in a seperate folder from yours.
- Use FileExists() to determine if the folder in your temporary seperate folder exists.
   - If No, use CFFILE to move the file from TMP to ORIGINAL and do your thing.
   - If Yes, pass file name using hidden field to another form that has "File Exists, Overwrite?"
      - If user selects "Yes" here, then use CFFILE to move the file to the ORIGINAL folder, overwriting what's there.
      - If user selects "No" here, then use CFFILE to move the file to the ORIGINAL folder with a new name, alert user.
      - If user selects "Cancel", use CFFILE to delete the upload.

Not sure how you want the logic to work for No and Cancel, so what I said above can obviously be changed.  Another thing you'd have to do is make sure you cleaned up the temporary seperate folder, since a user could potentially close the browser instead of Selecting Yes/No/Cancel.

Another suggestion could be to have the radio button on the first form (overwrite file if exists? Yes / No) instead of on a seperate page, that way you will know before you have to check if you need to overwrite or not.
0
 
MichaelEvangelistaAuthor Commented:
I dont have time to test it today but I know the logic is right and this will work.
Answer accepted!
0
 
usachrisk1983Commented:
Thanks Michael :)
0
 
MichaelEvangelistaAuthor Commented:
Thank YOU Chris!
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

  • 10
  • 6
Tackle projects and never again get stuck behind a technical roadblock.
Join Now