apache-nifi

Nifi multipart form


I’m trying to do a simple multipart-form post to an API. I can’t see any way of doing this in Apache Nifi since it only seems to have one input for form data. There seem to be a lot of existing questions about this on here and the Nifi forum but none of them have any answers.

Is there a way to build multiple form data before I put it into InvokeHttp?


Solution

  • You could use ExecuteGroovyScript processor with the following code to build multipart/form-data:

    @Grab(group='org.apache.httpcomponents', module='httpmime', version='4.5.9')
    
    import org.apache.http.entity.mime.MultipartEntityBuilder
    import org.apache.http.entity.ContentType
    
    def ff = session.get()
    if(!ff)return
    
    def multipart
    
    ff.write{streamIn, streamOut->
        multipart = MultipartEntityBuilder.create()
            //specify multipart entries here
            .addTextBody( "username", ff.filename ) //get from flowfile attribute "filename"
            .addTextBody( "secret", new File("./README").getText("UTF-8") ) //add text body from file
            .addBinaryBody( "avatar", streamIn, ContentType.DEFAULT_BINARY, ff.filename )   //add flowfile content as binary body
            .build()
        multipart.writeTo(streamOut)
    }
    //set the `mime.type` attribute to be used as `Content-Type` in InvokeHTTP
    ff."mime.type" = multipart.getContentType().getValue()
    REL_SUCCESS << ff
    

    check the other add* methods to add multipart parameters: org.apache.http.entity.mime.MultipartEntityBuilder


    To check this code I used InvokeHTTP processor just after ExecuteGroovyScript with only following parameters changed: