About:
There are many blogs which discuss on how to do file transfer in JAX-RS /Restful service all this blogs discuss using the Multipartformdata i.e. FormDataParam as the input Stream.
In this Blog, I will be discussing on one of the way about how to create a service which will accept the File Object as input for the method which it consumes in the form XML.
Code:
Bean Class
package model;
import java.io.InputStream;
import javax.activation.DataHandler;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class FileData {
public FileData() {
super();
}
String fileName;
byte[] fileInfo;
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileName() {
return fileName;
}
public void setFileInfo(byte[] fileInfo) {
this.fileInfo = fileInfo;
}
public byte[] getFileInfo() {
return fileInfo;
}
}
Service Class
package model;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
@Path("model")
public class FileService {
public FileService() {
super();
}
@POST
@Consumes("application/xml")
public void uploadFile(FileData fd) {
try {
OutputStream os = new FileOutputStream("" + fd.getFileName());
InputStream is = new ByteArrayInputStream(fd.getFileInfo());
byte[] buffer = new byte[1024];
int bytesRead;
//read from is to buffer
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
is.close();
//flush OutputStream to write any buffered data to file
os.flush();
os.close();
} catch (Exception e) {
System.out.println("Inside the Service"+e);
}
}
}
For Client :
I will explain in another blog on how to consume this in REST DataControl / URL DataControl
Great work, thanks Alex!
ReplyDelete