How to upload a file in REST API

This is how I define the method: @POST @Path("/upload") @Consumes(MediaType.MULTIPART_FORM_DATA) ActionStatus uploadFile(@Multi...

This is how I define the method:
ActionStatus uploadFile(@MultipartForm FileUploadForm form);

And then the implementation:
public ActionStatus uploadFile(FileUploadForm form) {
 File file = new File(getRootDir() + File.separator + form.getFilename());

 try {
  if (!file.exists()) {

  FileOutputStream fop = new FileOutputStream(file);


  if (FilenameUtils.getExtension(file.getName()).equals("zip")) {
   // unzip
   // get parent dir
   String parentDir = file.getParent();
   FileUtils.unzipFile(parentDir, new FileInputStream(file));

 } catch (Exception e) {
  // handle exception

Here's the FileUploadForm class:
public class FileUploadForm {

 private byte[] data;

 private String filename;

 public String getFilename() {
  return filename;

 public void setFilename(String filename) {
  this.filename = filename;

 public byte[] getData() {
  return data;

 public void setData(byte[] data) { = data;

To upload a file you must define 2 form-data variables in your form: filename (text) and uploadedFile (File). In Chrome's plugin Postman, you can set it in Body tab. Postman is great a tool for testing REST api.

*REST dependencies come from :* and org.jboss.resteasy.annotations.providers.multipart.*.


javaee-rest 194471455630027550

Post a Comment Default Comments