Question

I am using groovyx.net.http.HTTPBuilder to POST from Grails to a PHP script. I need to attach a couple of text fields and a number of files.

I can attach a few textfields this way with great success:

    MultipartEntity mpc = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE)
    mpc.addPart("json", new StringBody(json.toString()))

But, when I attach a file like this, the textfields are no longer present in the request:

        passFiles.each() { key, value ->
            mpc.addPart(key, new InputStreamBody(value.stream, value.type, value.filename))
            System.out << value
        }

I think the file should be okay to add this way. Here is my trace from the above:

[filename:icon.png, stream:java.io.ByteArrayInputStream@2747ebcb, type:image/png]

How can I cause HTTPBuilder to make this Multipart POST as intended?

Was it helpful?

Solution 2

Andrew's comment caused me to take a better look at the HTTPClient Java API. I was able to make everything work as above like this:

  1. Save a temporary copy of the stream to a file.

    def file = new File('web-app/tmpfiles/file.dat').newOutputStream()
    file << stream
    file.close()
    
  2. Instead of using InputStreamBody, use FileBody with the path to the saved file.

    mpc.addPart(key, new FileBody(new File('web-app/tmpfiles/file.dat'), filename, type, 'UTF-8'))
    

OTHER TIPS

A few thoughts:

  1. Did you remember to call setEntity() to link your request with your MultipartEntity?
  2. Depending on the version of Grails/Groovy you're using, you may be running into issue(s) in HTTPBuilder, described here. That link points to a patched fork, which I haven't tried.
  3. It's less than Groovy, but I've been able to accomplish a similar task from Grails with code that sticks closely to the Apache HTTPClient Java API.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top