Solved

ReReplace to remove spaces on upload?

Posted on 2006-07-11
17
1,075 Views
Last Modified: 2013-12-24
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
Comment
Question by:MichaelEvangelista
  • 10
  • 6
17 Comments
 
LVL 3

Expert Comment

by:siva350
ID: 17088335
Try replacing
<cfset realFileName = "#Rereplace(realFileName,"[[:space:]]","-","ALL")#">

With
<cfset realFileName = "#Rereplace(realFileName," ","-","ALL")#">
0
 

Author Comment

by:MichaelEvangelista
ID: 17088405
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
 
LVL 13

Expert Comment

by:usachrisk1983
ID: 17090139
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
 

Author Comment

by:MichaelEvangelista
ID: 17091444
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
 

Author Comment

by:MichaelEvangelista
ID: 17091452
I am on winXP
0
 

Author Comment

by:MichaelEvangelista
ID: 17091656
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
 

Author Comment

by:MichaelEvangelista
ID: 17092027
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
 
LVL 13

Expert Comment

by:usachrisk1983
ID: 17094807
<!---- 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
How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

 
LVL 13

Expert Comment

by:usachrisk1983
ID: 17094814
Sorry, take that back, I see it's not an upload problem but a rename problem.
0
 

Author Comment

by:MichaelEvangelista
ID: 17095049
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
 

Author Comment

by:MichaelEvangelista
ID: 17095138
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
 
LVL 13

Expert Comment

by:usachrisk1983
ID: 17099023
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
 

Author Comment

by:MichaelEvangelista
ID: 17099459
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
 
LVL 13

Accepted Solution

by:
usachrisk1983 earned 250 total points
ID: 17099812
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
 

Author Comment

by:MichaelEvangelista
ID: 17099855
I dont have time to test it today but I know the logic is right and this will work.
Answer accepted!
0
 
LVL 13

Expert Comment

by:usachrisk1983
ID: 17100012
Thanks Michael :)
0
 

Author Comment

by:MichaelEvangelista
ID: 17100057
Thank YOU Chris!
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

A web service (http://en.wikipedia.org/wiki/Web_service) is a software related technology that facilitates machine-to-machine interaction over a network. This article helps beginners in creating and consuming a web service using the ColdFusion Ma…
If you don't have the right permissions set for your WordPress location in IIS, you won't be able to perform automatic updates. Here's how to fix the problem.
This video explains how to create simple products associated to Magento configurable product and offers fast way of their generation with Store Manager for Magento tool.
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now