Search code examples
javafilegoogle-app-enginerestrestlet

Restlet & MULTIPART_FORM_DATA or another way to put files on Google App Engine via Restlet


I tried to receive files via restlet but only gets the complete MULTIPART_FORM_DATA. How can I extract my specific file?

I found some code-blocks but the types of them are not available... RESTlet: How to process multipart/form-data requests?

DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1000240);

// 2/ Create a new file upload handler
RestletFileUpload upload = new RestletFileUpload(factory);

My current code:

@Put
public void handleUpload(Representation entity) {
    if (entity !=null) {
        if (MediaType.MULTIPART_FORM_DATA.equals(entity.getMediaType(), true)) {
            Request restletRequest = getRequest();
            Response restletResponse = getResponse();
            HttpServletRequest servletRequest = ServletUtils.getRequest(restletRequest);
            HttpServletResponse servletResponse = ServletUtils.getResponse(restletResponse);

            try {
                Upload2(restletRequest, entity);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

public void Upload2(Request req, Representation entity) throws IOException
{
    ...
        GcsOutputChannel outputChannel = gcsService.createOrReplace(fileName, GcsFileOptions.getDefaultInstance());
        ObjectOutputStream oout = new ObjectOutputStream(Channels.newOutputStream(outputChannel)); 
        copy(entity.getStream(), oout);
        oout.close(); 

After storing with this method I have something like that and I only want to store the content with the name "picture":

��z------WebKitFormBoundarysOvzWKPqyqW7DiTu
Content-Disposition: form-data; name="picture"; filename="_MG_4369.jpg"
Content-Type: image/jpeg

����*ExifII*

As far as I read parsing of multipart form data isn’t supported yet? But there must be a solution to send files via restlet

I tried the rest-calls via postman for chrome. The is only on multiparts the support for files. Is a possible solution to send the image as a raw-text?


Solution

  • You will need to add Exception handling and deal with the InputStream and potentially clean up of temp files (see DiskFileItemFactory docs) but the basics are as follows, when using the org.restlet.ext.fileupload library.

    @Put
    public void handleUpload(Representation entity) {
        List<FileItem> items = new RestletFileUpload(new DiskFileItemFactory())
                     .parseRepresentation(representation);
        for (FileItem item : items) {
            if (!item.isFormField()) {
                MediaType type = MediaType.valueOf(item.getContentType());
                InputStream inputStream = item.getInputStream();
            }
        }
    }
    

    for a gae Solution try replacing the DiskFileItemFactory with a gwtupload.server.MemoryFileItemFactory.