I have made a rest api in this it is working fine but i want to read size of file and i have used below code to read size of file
@POST
@Path("/test")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response upload( FormDataMultiPart form ){
System.out.println(" size of file="+ filePart.getContentDisposition().getSize());
}
but i got the size of file -1 .
Can any one suggest me how can i read actual size of file .
But using
System.out.println(" data name ="+ filePart.getContentDisposition().getFileName());
i got correct name of file .
Hope this is what you wanted. I have verified it in my system. This prints the size of the file in bytes.
@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(@FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail) {
String uploadedFileLocation = "/home/Desktop/" + fileDetail.getFileName();
// save it
writeToFile(uploadedInputStream, uploadedFileLocation);
File file = new File(uploadedFileLocation);
System.out.println(file.length() + " in bytes");
String output = "File uploaded to : " + uploadedFileLocation;
return Response.status(200).entity(output).build();
}
// save uploaded file to new location
private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) {
try {
OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
make sure you have the following dependency in your pom.xml
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>2.13</version>
</dependency>
also add this to your application class which extends resource config. This registers your class with jersey as having multipart content.
super(YourClass.class, MultiPartFeature.class);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With