Validating a file type

Hi,
I have a form where files are uploaded to a server. I need to
prevent certain file types from getting uploaded (e.g, .exe etc.)
How can I validate the extention of the "upload_file" in the action
page when the temporary location of the file is gibberish. In the
action page, this is what is passed for the "upload_file" value:
/opt/jrun4/servers/cfusion/SERVER-INF/temp/cfusion-war-tmp/neotmp6417.tmp
Here's the form:
<cfform action="action.cfm" method="post"
enctype="multipart/form-data">
<cfinput name="upload_file" required="Yes" message="Please
upload a file.">
....

Thanks very much. I wrapped the entire thing in
<cftry>/<cfatch>.

Similar Messages

  • Server side validation for file type with cffil sent via cfmail problem

    Hello;
    I have a small app that I need to allow users to be able to use a form, and send me and email with a file attachment. I have it working nicely, I included file manipulation into the validation process of the form and required form fields. The problem I'm having, is this. I'm trying to create and instance where if they try and upload lets say a pdf, it throws and error: "You are trying to upload the wrong file, please try again we only accept bla bla bla" Problem is, even if I'm uploading the proper file, it's rejecting it and deleting it. Can someone help me fix this? I've tried a number of different ways and can't seem to get this to go off properly. I am posting some of the code. There is a ton, so I'm posting the main parts so you get the idea and see my variables.
    <!--- Declairing my variables and setting up form validation--->
    <cfparam name="FORM.descript" type="string" default=""/>
    <cfparam name="FORM.attachment_1" type="string" default=""/>
    <cfset arrErrors = ArrayNew( 1 ) />
    <cfset showForm = true>
    <cfif structKeyExists(form, "sendcomments")>
    <cfif NOT len(trim(FORM.name))>
    <cfset ArrayAppend(arrErrors,"Your Full Name!<br>") />
    </cfif>
    <!--- This is where the file error control is as you can see how the name is validated, the file will be dealt with in a similar maner--->
    <cfif NOT Len(Trim(FORM.attachment_1))>
    <cfset ArrayAppend(arrErrors,"You didn't attach a file!<br>") />
    <cfelseif ArrayLen( arrErrors )>
    <cftry>
    <cffile action="DELETE" file="#FORM.resume#"/>
    <cfcatch>
    <!--- File delete error. --->
    </cfcatch>
    </cftry>
    <cfelse>
    <!--- no errors with the file upload so lets upload it--->
    <cftry>
    <cfset request.AcceptImage="image/gif,image/jpg,image/jpeg,image/pjpeg,image/x-png">
    <cffile action="upload"
                     filefield="attachment_1"
                     accept="#request.AcceptImage#"
                     destination="c:\websites\187914Kg3\uploads\"
                     nameconflict="Makeunique">
    <!---
    Now that we have the file uploaded, let's
    check the file extension. I find this to be
    better than checking the MIME type as that
    can be inaccurate (so can this, but at least
    it doesn't throw a ColdFusion error).
    --->
    <cfif NOT ListFindNoCase("request.AcceptImage",CFFILE.ServerFileExt)>
    <cfset ArrayAppend(arrErrors,"Only JPEG, GIF, and PNG file formats are accepted!<br>") />
    <!---
    Since this was not an acceptable file,
    let's delete the one that was uploaded.
    --->
    <cftry>
    <cffile action="DELETE" file="#CFFILE.ServerDirectory#\#CFFILE.ServerFile#"/>
    <cfcatch>
    <!--- File Delete Error. --->
    </cfcatch>
    </cftry>
    </cfif>
    <!--- This is the code that is causing my problem. The above code is saying everything is not the proper file and rejecting it all--->
    Can anyone help me out. I can make more of this code available if needed. Like i said, there's a lot and I didn't want to dump it all out, this is the section creating the problem. There are no errors at this time, just rejecting all file types.
    thank you.

    It appears you are comparing your content_length with 1MB.
    1KB: 1024 bytes
    1MB: 1024*1024 bytes
    Let us use max allowable size of 25KB here and amend the second half of our code.
    <!--- Set max allowable file size in KB at the top --->
    <cfset maxFileSize = 25>
          <!--- Check if file is an image file of acceptable size --->
          <cfif (#reFindNoCase("gif|jpg|jpeg|pjpeg|png",myResult.clientFileExt, 1)# EQ 1) AND (#myResult.FileSize# LTE (#maxFileSize#*1024))>
                <!--- Retain if right file type and size --->
                <p>
                Your file <strong>#myResult.clientFile#</strong> has been uploaded successfully!<br />
                <a href="yourTemplate.cfm">Back</a></p>
                <!--- Otherwise if wrong type --->
          <cfelseif #reFindNoCase("gif|jpg|jpeg|pjpeg|png",myResult.clientFileExt, 1)# NEQ 1>
                <p>
                You are trying to upload a <strong>#myResult.clientFileExt#</strong> file, please try again. We only accept <strong>gif, jpg, jpeg, and png</strong>.
                </p>
                <!--- Delete unacceptable file and show form to user to try again--->  
                <cffile action="delete"  file="#svrFile#" />
                      <form method="post" action=#cgi.script_name# 
                      name="uploadForm" enctype="multipart/form-data">
                      <input name="attachment_1" type="file">
                      <br>
                      <input name="submit" type="submit" value="Try again!">
                </form>
                <!--- Or size too large --->
          <cfelseif #myResult.FileSize# GT (#maxFileSize#*1024)>
                <p>
                Your file was too large (<strong>#numberFormat(myResult.fileSize/1024, "____.__")# KB</strong>). Please try a smaller file!
                </p>
                <!--- Delete file and show form--->
                <cffile action="delete"  file="#svrFile#" />
                      <form method="post" action=#cgi.script_name# 
                      name="uploadForm" enctype="multipart/form-data">
                      <input name="attachment_1" type="file">
                      <br>
                      <input name="submit" type="submit" value="Try again!">
                </form>
          </cfif>
    </cfif>        <!--- Closes the cfif tag which started from the first half --->
    </cfoutput><!--- ditto --->

  • Photo will not upload my pictures from the same camera that always worked in IPhoto.  Says "could not be imported (may be unrecognized file type or files may not contain valid data).  So how do I do it?

    Photo will not upload new photos from same camera that always worked in IPhoto.  Says "could not be uploaded )may be unrecognized file type or files may not contain valid data).  Help!

    Try image capture or a card reader - after the photos are safely on your Mac then use the camera's format command to reformat the memory card
    LN

  • Validation of the file type being uploaded

    Hi,
    My requirement is to put a validation on the Primary File metadata field so that it allows only certain type of file types.
    Example the primary file should allow only .doc and .pdf and restrict .jpeg/.tiff files
    Can any one suggest how this can be implemented ?
    Regards,
    Bhaskar

    You will want to write a validateStandard filter. This will run during the checkin of files.
    In the filter you can write code such as:
    String filename = binder.getLocal("primaryFile");
    Then you can strip that filename String and find the file extension. You can build a list in the actual Java filter that allows/disallows certain filetypes. You could also have this allow/disallow list as a checked-in piece of content (e.g. an XML document) or you could set this as a preference prompt.
    Simply looking at the file extension is not bulletproof. You would need to examine the MIME type if you want better security.
    This thread linked below has links to the HowTo components which will show you how to implement a filter.
    Filter Implementation
    Jonathan
    http://redstonecontentsolutions.com
    http://corecontentonly.com

  • "uses a file type that is blocked from opening in this version" error message when opening a *.doc file with Word already running

    Several customers running different versions of Office 2011 (14.4.1-14.4.5) on OSX varying from 10.7.5 to 10.9.5, running on various kinds of hardware (iMac/MacBook Pro/MacBook Air) of various ages are having issues opening *.doc files if the Word is already open. The error message that gets displayed is, "XXXX.doc uses a file type that is blocked from opening in this version"
    When the customer tries to open the same file via File-Open, she gets "The file is locked for editing. you can open the file as read-only".
    When trying to do so, she gets "Word cannot open this document. The document might be in use, the document might not be a valid Word document, or the file name might contain invalid characters".
    If Word gets Force-quit, the same document opens without any problems.
    1. Repairing Disk permissions was ran several times. and the volume was found to be OK.
    2. I have noticed that in this scenario either deleting the normal.dotm or com.microsoft.word.plist (~/Library/Preferences) sometimes resolves the issue, sometimes it doesn’t. There is no pattern to follow. All versions of Office are affected, the fully updated and the non-updated ones.
    3. I have tried completely removing the suite using Office 2011 Uninstall.app and/or Remove Office 2011 Uninstaller.pkg, then going through customer's library and manually removing all the Office references.
    4. None of these systems had Office 2008 in the past.
    Any help will be greatly appreciated.

    Reboot both the Mac and the server. Word opens .DOC files and Excel opens .XLS files. As you have found out by copying the files to the computer. It is the connection between the 2 computer that is causing the error.

  • XML Publisher question - Not generating a valid XML file

    I am working through an Oracle document that walks you through creating an XML Pub report. I am using HCM 8.9, Tools 8.49.15 and it has XML Pub installed and I have the Microsoft plug-in installed
    I have created a query and have downloaded an rtf template and now am on a page where you enter your data source and then click ‘Generate’ for the sample data file. I did it and it created ‘PERSONAL_DATA_PAY.XML’ which is created from a PS Query. However if I click on ‘PERSONAL_DATA_PAY.XML’ it generates a blocky text file that is not an XML file and I can’t go any further.
    Do you know why it’s not generating a valid XML file when I click on 'generate'?
    Thanks
    Allen H. Cunningham
    Data Base Administrator - Oracle/PeopleSoft
    Sonoma State University

    You mean to say that you create a new data source by specifying Data Source Type as 'PS Query' and Data Source ID as your query name, you are not able to generate a valid XML file (by clicking on Generate link).
    did you cross check your query by running it?
    On field change of Generate link, PeopleSoft uses PSXP_RPTDEFNMANAGER and PSXP_XMLGEN app packagaes and query objects to create the file
    It should work if you query is valid..

  • Detecting file type in vba for word

    I have directories full of files on a Mac.  Most of these files are Doc files, some Txt files and some other types. Unfortunately the files don't have file extensions (not hidden but actually no file extensions).  On a PC in a macro I need to open
    these  doc files (from the Mac) and do some manipulations on the files and then save them.  I have a macro which works as long as all the files are Doc files so if I can detect the file type in my macro I can skip the non-Doc files and process only
    the Doc files.
    Is there a way in a vba for word macro to detect a file type other than by the file extension?  Or if that can't be done can I put error trapping on my Open statement that will catch an attempt to Open a non-Doc type file?
    Thanks
    Harry Spier

    If your code is running on Windows and you are in a position to install software on it, you
    may be able to get reasonably reliable detection using dsofile.dll, which you can get here:
    I really do not know whether it will work with files stored or create on Mac (and in any case, if these are old Mac .doc files, you may find that Windows Word cannot open them anyway.
    You need to
     - register the dll via regsvr32
     - in VBE, use Tools->References... to make a reference to"DSO OLE Document Properties Reader 2.1"
     - use code such as the sample below. 
    Option Explicit
    Function IsWordDoc(FullName As String) As Boolean
    ' FullName is the full path name of the file you want to check
    Dim objDocumentProperties As DSOFile.OleDocumentProperties
    IsWordDoc = False
    Set objDocumentProperties = New DSOFile.OleDocumentProperties
    ' or you can add dsoOptionOnlyOpenOLEFiles to the options and
    ' use error trapping to detect -2147217148
    objDocumentProperties.Open sFileName:=FullName, ReadOnly:=True, Options:=dsoOptionDontAutoCreate
    If objDocumentProperties.IsOleFile Then
    If objDocumentProperties.OleDocumentFormat = "MSWordDoc" Then
    IsWordDoc = True
    End If
    End If
    objDocumentProperties.Close savebeforeclose:=False
    Set objDocumentProperties = Nothing
    End Function
    Sub testIsWordDoc()
    Debug.Print IsWordDoc("c:\a\test.doc")
    Debug.Print IsWordDoc("c:\a\test.xls")
    End Sub
    You may also find that the value of the property I am checking varies and that you need to look at other things, such as 
    objDocumentProperties.SummaryProperties.ApplicationName
    but that value definitely varies according to the version of Word used to create the .doc, so you would need to discover what values it can have in a valid .doc.
    Peter Jamieson

  • File type associations is not working in the App-V 4.6 SP3

    Hello,
    I found issue, that file type associations is not working in App-V 4.6 SP3. When I try to open associated file with double click I receive next window:
    Translate: This action is only valid for products that are currently installed.
    I have checked associations in App-V Console and in OSD file, everything looks like OK.
    Maybe someone has some ideas?
    Could you please share them with me?
    Thank you in advance.

    Is this only happening on one client machine? If so can you completely clear the application and re-stream\cache it again?
    If that fails, you could try to create the FTA locally on the client
    PLEASE MARK ANY ANSWERS TO HELP OTHERS Blog:
    rorymon.com Twitter: @Rorymon

  • Can't download .GZ file - incorrect file type?

    Thank you for helping me. Using the code below, I am trying to access a log file from a site (log.gz) and download it to my hard drive to expand and analyze locally. When I try to expand the file, the message says that it does not recognize the file type. I suspect that it is adding in errant bits of data. Is there some way to make it keep the data structure intact?
    Thanks,
    Greg
    import java.net.*;
    import java.io.*;
    import java.util.Date;
    public class SaveWebFile{
    public static void main(String[] args) {
         String username = "xxxx";
         String password = "xxxxx";
    String authorization = username + ":" + password;
    sun.misc.BASE64Encoder enCoder = new sun.misc.BASE64Encoder();
    String encodedAuthorization = "Basic " + enCoder.encode(authorization.getBytes());
    try{
         URL url = new URL("http://www.test.com/logs/dailylog.gz");
         HttpURLConnection con = (HttpURLConnection)url.openConnection();
         con.setRequestProperty("Authorization", encodedAuthorization);
         InputStreamReader in = new InputStreamReader (con.getInputStream());
         OutputStream out = new FileOutputStream( "c:\\logs\dailylog.gz" );
         int b;
         while( (b = in.read()) != -1) out.write( (byte)b );
         in.close();
         out.close();
         } catch (MalformedURLException e) {
         System.out.println (" is not a valid URL.");
         System.exit(1);
         } catch (IOException e) {
         System.out.println ("Unable to connect");
         System.exit(1);
    }

    Does this fix it?
    BufferedInputStream in = new BufferedInputStream(con.getInputStream());
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("log.gz"));
    final int NUM_BYTES = 32768;
    int numBytesRead = 0;
    byte[] buf = new byte[NUM_BYTES];
    while( (numBytesRead = in.read(buf, 0, NUM_BYTES)) != -1)
      out.write(buf, 0, numBytesRead);
      out.flush();
    out.close();
    in.close();

  • Not a valid SOAP Content-Type: text/html; charset=iso-8859-1

    Friends
    JDEV and SOA suite 10134
    I have multiple domains on my BPEL Server. In one of the domain since I deployed the new process, all the processes of that domain are now failing on execution with following error in opmn/soa_instance/*.err log files. No errors in domain.log
    +"Caused by: java.security.PrivilegedActionException: oracle.j2ee.ws.saaj.ContentTypeException: Not a valid SOAP Content-Type: text/html; cha+
    +rset=iso-8859-1"+
    At the same time we get Internal Server Error on BPEL Console.
    I have sync processes with 1 or two invokes, so I am generally losing the instances, cannot provide the details in the process execution. All BPEL processes are invoking Siebel Web Services, that is the common part.
    When I restart my system, it may or may not work; even if it works then within few instances execution again starts giving the same error. I can see that after the errors the instance are going through and getting completed successfully few times. All these processes were working successfully earlier.
    Any idea about this !!!!
    Thanks

    Thanks Anirudh,
    I don't use compensation handlers. Moreover I have properly defined the scopes and sequences throughout the bpel process. My processes are sync in nature and I'm not able say at what step exactly the processes are failing and throwing the SOAP content Type error though the instances are getting completed with delay soemtimes.

  • Oracle Business Rules :  File Type Rules Repository Creation Problem

    Hi Gurus,
    I am trying to create File Type Rules Repository(SOA Suite 10.1.3.3).
    As per the documentation:user Guide
    Oracle Business Rules supplies a blank file repository that does not contain a dictionary. This file repository is named "emptyFileRepository" and is located in the
    $ORACLE_HOME/rules/lib directory.To setup a new file repository, copy and rename the emptyFileRepository file.
    Then, provide this file name and location in the Repository Connect page
    I did the same thing.I copied the emptyFileRepository and renamed the file.After giving the file location and click on the Create button it is throwing the error "Please provide a valid directory path." Please Help me to fix this.
    The same kind of the question was posted on the same forum which was un answered.Please guide me to fix the problem.I googled a lot but no help found.
    please route me to proper source.
    Thanks in advance..
    Regards,
    ravi

    I was able to create repository for business rules few weeks ago perhaps I was using an old version of the firefox, now I upgraded to firefox 3.5.7 and get the same error. IE 7 hangs, did you get a solution yet?
    I am planning to downgrade my firefox and give it a try. Please update if you find a fix.

  • Trying to find answers for the question "Why is this file type blocked from being uploaded into SharePoint"

    At least once a month - sometimes much more frequently - I get calls from users asking why the file extension they "need" to upload to SharePoint is blocked.
    Most recently, it was a Microsoft Access database that the user was attempting to upload to a document library. Before that, it was a shortcut link (*.url). And so on.
    Is there a reference document which goes over the reasons why specific file types are blocked?
    Thanks!

    Each blocked file format has it's own reasons for not being allowed to be stored on a SharePoint library.
    Some of them are blocked because they would be processed by SharePoint Servers during the upload/download sequences, thus, possibly corrupting the system ( like dll files ). Others would cause Crawl to break ( url files ).
    The Access database files are blocked for two valid reasons. First, because saving "live" to those files using Windows explorer window ( WebDAV ) doesn't work. Second because SharePoint product managers want us to use SharePoint lists instead.
    And it does makes sense.
    If you're in the middle of a migration from file servers to a SharePoint solution, your people could use these situations to stop and think about it for a little:
    Really ? Now that we have SharePoint, couldn't we do things a little bit differently ?

  • ORA-6522 -- module: Bad object file type

    Hello!
    I have created a external procedure. When I call it I get the following message:
    ORA-06522: '/sys/app/oracle/product/9.2.0/lib/shell.o' is not a valid load
    module: Bad object file type
    I cannot find anything explaining what "Bad object file type" means. Do you have any suggestions?

    Hello!
    I have created a external procedure. When I call it I get the following message:
    ORA-06522: '/sys/app/oracle/product/9.2.0/lib/shell.o' is not a valid load
    module: Bad object file type
    I cannot find anything explaining what "Bad object file type" means. Do you have any suggestions?

  • Error  in validation.xml   file while deploying in server

    Hi friends,
    I am Venkataramana . I am doing one small structs application with Validation . as usual in XML file i wrote validations but when i am deploying in server it is showing error as
    SEVERE: Parse Error at line 2 column 17: Document is invalid: no grammar found.
    org.xml.sax.SAXParseException: Document is invalid: no grammar found.
         at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:236)
    and
    Jan 11, 2010 11:57:53 PM org.apache.commons.digester.Digester error
    SEVERE: Parse Error at line 2 column 17: Document root element "form-validation", must match DOCTYPE root "null".
    org.xml.sax.SAXParseException: Document root element "form-validation", must match DOCTYPE root "null".
    Kindly find the validation.xml file for your reference.
    <!DOCTYPE form-validation PUBLIC
    "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN"
    "http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd">
    <form-validation>
    <formset>
    <form name="regFormForm">
    <field property="username"
    depends="required">
    <arg0 key="uname"/>
    </field>
    <field property="password"
    depends="required">
    <arg0 key="password"/>
    </field>
    </form>
    </formset>
    </form-validation>
    Please can any one help on this?

    I think your dtd entry - "http://jakarta.apache.org/commons/dtds/validator_1_1_3.dtd" is not compatible with your validation.jar file. If you have recently downloaded the these struts jar files then make sure this entry is matched with what they have provided in examples. Or download new set of jar files and copy the same doc-type tag as they have given in examples.

  • Unrecognized file type

    There's a few posts on this topic but no conclusive answers.
    When I try to import into iPhoto 08 i get the following message -
    "The following files could not be imported (they may be an unrecognized file type of the files may not contain valid data).
    I copied the photos to my desktop andtried again but same results.
    The jpg's are find and FINDER can view them. There wasr no problem last week but now??
    As an example the address of the files shown in the dialog box reads as follows -
    /private/var/folders/zz/ZZy5x7B9EI8VU0rHf5s-Lk+TI/-Tmp-/iPhoto/P1020462.jpg.
    There was also an upgrade from Apple I believe earlier this week?? - thanks.

    Have you run Disk Utility to repair disk permissions on your HD? You might also try deleting the iPhoto preference file, com.apple.iPhoto.plist. It will be recreated when you launch iPhoto.
    TIP: For insurance against the iPhoto database corruption that many users have experienced I recommend making a backup copy of the Library6.iPhoto (iPhoto.Library for iPhoto 5 and earlier versions) database file and keep it current. If problems crop up where iPhoto suddenly can't see any photos or thinks there are no photos in the library, replacing the working Library6.iPhoto file with the backup will often get the library back. By keeping it current I mean backup after each import and/or any serious editing or work on books, slideshows, calendars, cards, etc. That insures that if a problem pops up and you do need to replace the database file, you'll retain all those efforts. It doesn't take long to make the backup and it's good insurance.
    I've created an Automator workflow application (requires Tiger or later), iPhoto dB File Backup, that will copy the selected Library6.iPhoto file from your iPhoto Library folder to the Pictures folder, replacing any previous version of it. There are versions that are compatible with iPhoto 5, 6, 7 and 8 libraries and Tiger and Leopard. Just put the application in the Dock and click on it whenever you want to backup the dB file. iPhoto does not have to be closed to run the application, just idle. You can download it at Toad's Cellar. Be sure to read the Read Me pdf file.
    NOTE: The new rebuild option in iPhoto 09 (v. 8.0.2), Rebuild the iPhoto Library Database from automatic backup" makes this tip obsolete.

Maybe you are looking for

  • Can't display java applet in IE?

    when I open the Internet Explore to display my applet,It' not display anything,only several small word in left corner: Load:SaveCert can't be instantiated. SaveCert is my class's name. Why?

  • Will a 500G hard drive work in my first generation G5?

    dual 2.0ghz? i plan to buy a 500g hard drive, and i thought i remembered reading somewhere that they couldn't handle them, but maybe i'm mistaken. thanks

  • Cant find button

    I get to the download page foradobe flash player and i cant see the download button. i think the black box at the top is covering it. can someone pleasseeee help me.

  • Recommendations for a small portable bluetooth mouse?

    Does anyone have recommendations for a small portable bluetooth mouse? There don't seem to be a lot out there.

  • Steps to create info cubes

    hi can u plz let me know what r the steps to create info cubes and ods and plz tell me stps to ods to info cubes regards sahsi