Support Questions

Find answers, ask questions, and share your expertise

Nifi Unzip files

avatar

Hello 

I need help

I want to unzip file.zip with NiFi

I have used unpackContent processor but that didn't work because of my nifi version 1.13

I have also used executeStreamCommand to execute python script but I didn't found until now the solution

Can you help me

 

Thanks

10 REPLIES 10

avatar
Explorer

@joseomjr 
your code could not work at my end. 
ChatGPT help me with below code and it is working at my end.

import java.util.zip.ZipInputStream
import java.util.zip.ZipEntry
import java.io.ByteArrayOutputStream

def flowFile = session.get()
if (!flowFile) return

try {
    session.read(flowFile, { inputStream ->
        ZipInputStream zipIn = new ZipInputStream(inputStream)
        ZipEntry entry = zipIn.nextEntry

        while (entry != null) {
            if (!entry.isDirectory()) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream()
                byte[] buffer = new byte[8192]
                int len
                while ((len = zipIn.read(buffer)) > 0) {
                    baos.write(buffer, 0, len)
                }

                def contentBytes = baos.toByteArray()
                def newFlowFile = session.create(flowFile)
                newFlowFile = session.write(newFlowFile, { outStream ->
                    outStream.write(contentBytes)
                } as OutputStreamCallback)

                newFlowFile = session.putAttribute(newFlowFile, 'filename', entry.getName())
                session.transfer(newFlowFile, REL_SUCCESS)
            }
            zipIn.closeEntry()
            entry = zipIn.nextEntry
        }

    } as InputStreamCallback)

    session.remove(flowFile)

} catch (Exception e) {
    log.error("Failed to unzip FlowFile due to: ${e.message}", e)
    session.transfer(flowFile, REL_FAILURE)
}

I hope there is no security concern with this code!