This week I had to unzip some files using ColdFusion 7 (I know it’s ancient technology) and I realised that CF7 doesn’t natively support zipping/unzipping of files! ?Fortunately, ColdFusion can utilise the underlying power of Java to achieve this. ?I found this neat Java article – Unzipping Files with java.util.zip.ZipFile and simply translated it into ColdFusion 7.
Here is the ColdFusion version that works well on CFMX7:
<cfparam name="dest" default="/path_to_extract/"> <cffunction name="getByteArray" access="private" returnType="binary" output="no"> <cfargument name="size" type="numeric" required="true"/> <cfset var emptyByteArray = createObject("java", "java.io.ByteArrayOutputStream").init().toByteArray()/> <cfset var byteClass = emptyByteArray.getClass().getComponentType()/> <cfset var byteArray = createObject("java","java.lang.reflect.Array").newInstance(byteClass, arguments.size)/> <cfreturn byteArray /> </cffunction> <cfscript> if(structKeyExists(form,"myFile") and len(form.myFile)) { content = ArrayNew(1); FileOutputStream = createObject('java',"java.io.FileOutputStream"); BufferedOutputStream = createObject('java',"java.io.BufferedOutputStream"); ZipFile = createObject('java',"java.util.zip.ZipFile"); ioFile = createObject('java',"java.io.File"); Byte = createObject('java',"java.lang.Byte"); buffer = getByteArray(1024); length = 0; zipFileName = form.myFile; zFile = ZipFile.init(zipFileName); entries = zFile.entries(); while(entries.hasMoreElements()) { entry = entries.nextElement(); if(entry.isDirectory()) { // Assume directories are stored parents first then children. ioFile.init(dest & entry.getName()).mkdir(); continue; } in = zipFile.getInputStream(entry); out = BufferedOutputStream.init(FileOutputStream.init(dest & entry.getName())); length = in.read(buffer); while(length gte 0) { out.write(buffer, 0, length); length = in.read(buffer); } in.close(); out.close(); } zFile.close(); //loop tghrough content array and decrypt } </cfscript> <form name="myForm" method="POST" action="zip.cfm" enctype="multipart/form-data"> <input type="file" name="myfile" /> <input type="submit" name="submit" value="Upload" /> </form>
Marko