Skip to content

Upload file on Jersey #3

@Magador

Description

@Magador

In your HTML form, you just need a form with a file input and a submit button:

<form method="post" action="path/to/servlet" enctype="multipart/form-data">
    <input type="file" required name="file"/>
    <input type="submit" />
</form>

Minimal HTML for single file upload.
Using Jersey.

@MultipartConfig(location = "path/to/file/directory", fileSizeThreshold = maxSizeOfFileOnDisk)
@Path("path/to/rest")
public class ImageResource {

    @Context
    HttpServletRequest req;

    @POST
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Path("upload")
    public Response uploadImage(@FormDataParam("file") InputStream file, @FormDataParam("file") FormDataContentDisposition fileDisposition) {
        // Directory + Filename + Extension
        String filePath = this.getClass().getAnnotation(MultipartConfig.class).location() + File.separator +
                          <FILE_NAME> +
                          fileDisposition.getFileName().substring(fileDisposition.getFileName().indexOf('.') + 1);
        try {
            OutputStream os = new FileOutputStream(new File(filePath));
            int read = 0;
            byte[] bytes = new byte[4096];
            while ((read = file.read(bytes)) != -1)
                os.write(bytes, 0, read);
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

This is the minimal required code for this to work.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions