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...
https://www.czetsuyatech.com/2017/09/javaee-rest-upload-file-using-rest.html
This is how I define the method:
And then the implementation:
Here's the FileUploadForm class:
*REST dependencies come from : javax.ws.rs.* and org.jboss.resteasy.annotations.providers.multipart.*.
@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
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()) {
   file.createNewFile();
  }
  FileOutputStream fop = new FileOutputStream(file);
  fop.write(form.getData());
  fop.flush();
  fop.close();
  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 {
 @FormParam("uploadedFile")
 @PartType(MediaType.APPLICATION_OCTET_STREAM)
 private byte[] data;
 @FormParam("filename")
 @PartType(MediaType.TEXT_PLAIN)
 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) {
  this.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 : javax.ws.rs.* and org.jboss.resteasy.annotations.providers.multipart.*.

 



 
 
 
Post a Comment