Skip to content
Advertisement

Uploaded file fails to save with no exception thrown in Java – Jersey

I’m trying to upload a file to a restful – Jersey web service deployed on Tomcat server that is a receives uploaded files as multipart . It works fully correct on Windows OS but on Linux the file fails to save with no exception thrown from the following saving method :

@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadProductImage(
        @FormDataParam("file") final InputStream uploadedInputStream,
        @FormDataParam("file") final FormDataContentDisposition cdh,
        @FormDataParam("file") final FormDataBodyPart body
) {
    FileManager fileManager = new FileManager();
    String fileName;

    try {
        int read = 0;
        byte[] bytes = new byte[1024];
        OutputStream out = new FileOutputStream(new File("/home/files"));

        while ((read = uploadedInputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        out.flush();
        out.close();
    } catch (IOException e) {

        e.printStackTrace();
    }

    return Response.status(Response.Status.CREATED).entity(gson.toJson(cdh.getName())).build();
}

The multipart variable is already declared in the web.xml file as :

<init-param>
        <param-name>jersey.config.server.provider.classnames</param-name>
        <param-value>org.glassfish.jersey.media.multipart.MultiPartFeature</param-value>
    </init-param>

As seen in the code the target path is “/home/files”.
I’m sure that the path exists and I already tried to change the owner of the target file to the tomcat group , and granted all the permissions to the path without any results. I appreciate your help.

Advertisement

Answer

So after working on this I found out that file write fails or permission errors are not thrown as exceptions , the code would work normally , and in this case what can be done to solve this type of problem is the following:

  1. Since the path is outside the war body it has to be indicated to within the server.xml file in the tomcat directory.
  2. The directory group has to be same as Tomcat group , it can be changed through chgrp command in linux terminal.
  3. Permission has to be granted to the directory’s group using the chmod command in linux.
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement