Search code examples
javaspringjersey

Jersey HTTP POST method corrupting non-text files


I have a HTTP POST method that works fine if I upload text files. But if I try to upload a word document, pdf, zip, gzip, etc... the files that are uploaded get corrupted in the process. I'm using Postman to send the request. I do a "POST" method, enter the url, add headers (tried all sorts of headers and it really does not change anything so now I don't have any entered), and then on the body I select "formdata" and select the file. I really just need to fix this to be able to support files that end in .csv.gz and .csv. Currently, csv is fine but the .csv.gz is the type that is corrupting. I tried other non-text files as well just to see what happens and they corrupt too. I cannot figure out if there is some encoding, filter, etc... that is causing this to happen that I can remove or some setting I need to apply. Or if there is some other way to handle this with jersey so the non-text files stay the same as the original file.

My application is running Spring v1.5.3 and Jersey 2.25.

    @Override
public Response uploadTopicFile(String topic, FormDataMultiPart formDataMultipart) throws Exception {
    List<BodyPart> bodyParts = formDataMultipart.getBodyParts();

    // Getting the body of the request (should be a file)
    for (BodyPart bodyPart : bodyParts) {
        String fileName = bodyPart.getContentDisposition().getFileName();
        InputStream fileInputStream = bodyPart.getEntityAs(InputStream.class);
        String uploadedFileLocation = env.getProperty("temp.upload.path") + File.separator + fileName;
        this.saveFile(fileInputStream, uploadedFileLocation);
        String output = "File uploaded to : " + uploadedFileLocation;
        log.debug(output);
    }
    return Response.status(201).build();
}

    private void saveFile(InputStream uploadedInputStream, String serverLocation) {
    try {

        // Create the output directory
        Files.createDirectories(Paths.get(serverLocation).getParent());

        // Get the output stream
        OutputStream outputStream = new FileOutputStream(new File(serverLocation));
        int read = 0;
        byte[] bytes = new byte[1024];

        // Loop through the stream
        while ((read = uploadedInputStream.read(bytes)) != -1) {
            // Output to file
            outputStream.write(bytes, 0, read);
        }

        // Flush and close
        outputStream.flush();
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return;
}

Solution

  • There was a filter causing the corruption. Filter was updated and issue resolved.