Comment on page
File Handling
CFML allows you to manipulate, read, upload, etc files via its built in methods which are great and easy to use. It can even help you manipulate zip/jar archives! We won't go into every single detail of file handling, but below you can find the majority of functions to deal with file handling.
- ExpandPath Creates an absolute, platform-appropriate path that is equivalent to the value of relative_path, appended to the base path. This function (despite its name) can accept an absolute or relative path in the relative_path attribute
- FileRead Reads an on-disk or in-memory text file or a file object created with the FileOpen function.
- FileSeek Shifts the file pointer to the given position. The file must be opened with seekable option
- FileSetAccessMode Sets the attributes of an on-disk file on UNIX or Linux. This function does not work with in-memory files.
- FileWrite If you specify a file path, writes the entire content to the specified file. If you specify a file object, writes text or binary data to the file object.
- FileWriteLine Opens up the file (or uses the existing file object) and appends the given line of text
- GetFreeSpace Returns the number of unallocated bytes in the partition named by this abstract path name.
- GetTempFile Creates a temporary file in a directory whose name starts with (at most) the first three characters of prefix.
// A few examples
content = fileRead( expandPath( "/config/myfile.txt" ) );
if( fileExists( "filepath.txt" ) ){
}
fileDelete( "filepath.txt" )
fileWrite( getTempFile( getTempDirectory(), "tempFile"), "My Data" );
directoryList( "/my/path" )
directoryExists( "/my/path" )
<form method="post" enctype="multipart/form-data">
<input type="file" name="fileInput">
<button type="submit">Upload</button>
</form>
<cfscript>
if( structKeyExists( form, "fileInput" )) {
try {
uploadedFile = fileUpload( getTempDirectory(), "fileInput", "image/jpeg,image/pjpeg", "MakeUnique" );
// check the file extension of the uploaded file; mime types can be spoofed
if (not listFindNoCase("jpg,jpeg", cffile.serverFileExt)) {
throw("The uploaded file is not of type JPG.");
}
// do stuff with uploadedFile...
} catch ( coldfusion.tagext.io.FileUtils$InvalidUploadTypeException e ) {
writeOutput( "This upload form only accepts JPEG files." );
}
catch (any e) {
writeOutput( "An error occurred while uploading your file: #e.message#" );
}
}
</cfscript>
stream = streamBuilder.new().ofFile( absolutePath );
try{
//work on the stream of lines of files and close it in the finally block
} finally{
stream.close();
}
//You can even process file lines concurrently
stream = streamBuilder.new()
.parallel()
.ofFile( absolutePath );
Last modified 2mo ago