cancel
Showing results for 
Search instead for 
Did you mean: 

[solved] multipart file upload with java backed webscript

mccarthymp
Confirmed Champ
Confirmed Champ
I have a java backed webscript that I am trying to use to upload a file into the Alfresco repository.  I can successfully see the uploaded file using a js controller and the formdata object.
i.e.
for each (field in formdata.fields) {
    logger.log(field.name);
    if(field.name == "file" && field.isFile) {
        logger.log(field.filename);
        logger.log(field.content);
        logger.log(field.mimetype);
    }
}

I attempted to create a FormData object inside my java backed web script but there are never any contents…
        if (req instanceof WebScriptServletRequest) {
            final WebScriptServletRequest webScriptServletRequest = (WebScriptServletRequest) req;
            final HttpServletRequest httpServletRequest = webScriptServletRequest
                    .getHttpServletRequest();
            final FormData formData = new FormData(httpServletRequest);

            //Get your files from formData because it is public by the patch:
            FormData.FormField[] fields = formData.getFields();
            logger.debug("is multipart? "+formData.getIsMultiPart());
            for(FormData.FormField field : fields) {
                logger.debug("field.getName(): "+field.getName());
                if(field.getName().equals("file")) {
                    String filename = field.getFilename();
                    Content content = field.getContent();
                    String mimetype = field.getMimetype();
                    logger.debug("filename: "+filename);
                    logger.debug("content: "+content);
                    logger.debug("mimetype: "+mimetype);
                }
            }
        }

Can anyone verify if you can upload multipart files using a java backed webscript and if so, any guidance would be appreciated.
1 REPLY 1

mccarthymp
Confirmed Champ
Confirmed Champ
This does work in 3.1 CE.  I'm not sure about others since I didn't test on other versions.  Instead of using an HttpServletRequest you must use the WebScriptRequest.  I hope this helps someone out.
      
        FormData formData = (FormData)req.parseContent(); // <– req = WebScriptRequest
        FormData.FormField[] fields = formData.getFields();
        for(FormData.FormField field : fields) {
                logger.debug("field.getName(): "+field.getName());
            if(field.getName().equals("file") && field.getIsFile()) {
                String filename = field.getFilename();
                Content content = field.getContent();
                String mimetype = field.getMimetype();
                logger.debug("filename: "+filename);
                logger.debug("content: "+content);
                logger.debug("mimetype: "+mimetype);
            }
       }