Showing posts with label receive file from server. Show all posts
Showing posts with label receive file from server. Show all posts

Tuesday, December 8, 2009

Download File From Server

We could retrieve/ download the file from the server and save it locally in to the PC.

public void downLoadFileFromDevice() throws IOException
{
final FacesContext ctx = FacesContext.getCurrentInstance();
if (!ctx.getResponseComplete())
{
InputStream fileFromEvox = null;
try
{
fileFromServer = receiveFile (“serverName/filename”);
}
catch (Exception e)
{
// Error Message.
 return;
}
final String contentType = "application/x-zip-compressed";
final StringBuilder sbuff = new StringBuilder(30);
sbuff.append(“newfilefromserver.xyz”);
final HttpServletResponse response = (HttpServletResponse)ctx
 .getExternalContext().getResponse();
response.setContentType(contentType);
response.setHeader("Content-Disposition",
 "attachment;filename=\"" + sbuff.toString() + "\"");
ServletOutputStream out = null;
InputStream istream = null;
try
{
istream = new BufferedInputStream(fileFromServer);
out = response.getOutputStream();
final byte[] buf = new byte[4096];
for (int c = istream.read(buf); c != -1; c =                
istream.read(buf))
{
out.write(buf, 0, c);
}}finally{
if(istream != null)
{istream.close();}
}
 out.flush();
 ctx.responseComplete();
}}
Receive file helps to establish the connections to the server and receives the file in the InputStream format

public InputStream receiveFile(final String uri)
throws EvoxException
{
try
{
final URL serverUrl = new URL(this.evoxServer + uri);
final HttpURLConnection connection =
 (HttpURLConnection) serverUrl.openConnection();
connection.setRequestMethod(RequestType.GET.name());
connection.setDoInput(true);
connection.setDoOutput(false);
// Read the Response
return connection.getInputStream();
}
catch (IOException exception)
{
throw new Exception("unable to receive file: " + uri,
 exception);
}}