Scriptrunner REST Endpoint MultiPart Form Data

I'm trying to upload a file to a scriptrunner REST custom end point. The file upload is being initiated from a dialog box with the following code

 

(function ($) {
    $("#dialog-close-button").click(function (e) {
        e.preventDefault();
        AJS.dialog2("#img-dialog").hide();
    });
    $("#img-form").submit(function(e) {
        var fd = new FormData($("#img-form").get(0));
        $.ajax({
            type: "POST",
            data: fd,
            url: "/rest/scriptrunner/latest/custom/adminImgUploadDialogSave",
            dataType   : 'json',
            processData: false,
            contentType: false,
            headers: {
                'Content-Type' : 'multipart/form-data',
                'X-Atlassian-Token': 'no-check',
                'Access-Control-Allow-Origin' : '*'
            },
        }).done(function(response) {
            if (response.status=="ok") {
                AJS.dialog2("#img-dialog").hide();
            }
        });
        e.preventDefault();
        return false;
    });
})(AJS.$);

In the rest endpoint I have

import com.onresolve.scriptrunner.runner.rest.common.CustomEndpointDelegate
import groovy.transform.BaseScript
import groovy.json.JsonBuilder
import javax.ws.rs.core.MultivaluedMap
import javax.ws.rs.core.Response
import javax.servlet.http.HttpServletRequest

@BaseScript CustomEndpointDelegate delegate

adminImgUploadDialogSave(
    httpMethod: "POST", groups: ["jira-administrators"]
) { MultivaluedMap queryParams, String body, HttpServletRequest req ->
    log.error("adminImgUploadDialogSave")
    log.error(body)
    log.error(req.getParts().toString())
    
    //if (filename==null) {
    //    return Response.ok(new JsonBuilder([status: 'not ok']).toString()).build()
    //} else {
    //    do stuff
    //    return Response.ok(new JsonBuilder([status: 'ok']).toString()).build()
    //}
}

body contains what I would expect

-----------------------------183231904016123
    Content-Disposition: form-data; name="atl_token"
    
    BD3R-R2T8-HXRR-WMXA|b2e4ac8fc23366985d8cb8d8b7e9e128d47a5c0b|lin
    -----------------------------183231904016123
    Content-Disposition: form-data; name="image"; filename="nodetype-child.png"
    Content-Type: image/png
    
    lots of binary data
    -----------------------------183231904016123--

but req.getParts() always returns an empty list.

How do I load/parse the form data?

 

 

 

 

 

1 answer

This widget could not be displayed.

Hey, Daniel. So, after hacking with this at length, I concluded that there's not a really robust way to do this with ScriptRunner out of the box. Like you, I was able to hack together something that handled uploading basic text files, but images proved more problematic. I've submitted a bug report for that. https://productsupport.adaptavist.com/browse/SRPLAT-211

We may just end up documenting a working example or pointing people to how to roll their own REST Endpoint using JAX, but you can watch that for further developments on multipart support in ScriptRunner REST Endpoints.

I ended up doing this

 

import com.onresolve.scriptrunner.runner.rest.common.CustomEndpointDelegate
import com.atlassian.jira.config.properties.ApplicationProperties
import com.atlassian.jira.component.ComponentAccessor
import groovy.transform.BaseScript
import groovy.json.JsonBuilder
import javax.ws.rs.core.MultivaluedMap
import javax.ws.rs.core.Response
import javax.servlet.http.HttpServletRequest
import java.io.FileOutputStream
import groovy.json.JsonSlurper
import java.util.regex.*

@BaseScript CustomEndpointDelegate delegate

TestImageUpload(httpMethod: "POST") { MultivaluedMap queryParams, String body, HttpServletRequest req ->
def params = new JsonSlurper().parseText(body)
Pattern re = Pattern.compile('^data:[^;]*;base64,(?<data>.*)$')
Matcher m1 = re.matcher((String)params['image'])
if (m1.matches()) {
String imageb64 = m1.group('data')
byte[] filedata = imageb64.decodeBase64()
String filename = '/var/something/somefile'
File file = new File(filename)
if (!file.exists()) {
file.createNewFile()
}
FileOutputStream fos = new FileOutputStream(filename)
fos.write(filedata)
fos.close()
return Response.ok(new JsonBuilder([status: 'ok']).toString()).build()
} else {
return Response.ok(new JsonBuilder([status: 'not ok']).toString()).build()
}
}

Suggest an answer

Log in or Sign up to answer
Community showcase
Published Aug 22, 2018 in Marketplace Apps

How a Marketplace app tech team is achieving gender diversity

Hello! My name is Genevieve Blanch, and I'm the Marketing Manager at RefinedWiki, creators of apps to give teams the tools to customize Atlassian platforms. Currently, 44% of the tech team at Re...

510 views 3 18
Read article

Atlassian User Groups

Connect with like-minded Atlassian users at free events near you!

Find a group

Connect with like-minded Atlassian users at free events near you!

Find my local user group

Unfortunately there are no AUG chapters near you at the moment.

Start an AUG

You're one step closer to meeting fellow Atlassian users at your local meet up. Learn more about AUGs

Groups near you