Wednesday, January 02, 2013

Android: Downloading a file to an external directory

In most of our applications we encounter a scenario where we have to download a file and then open it from our app. The file may be a pdf or an image.

So lets see the code for the same. I will be using the same HttpResponseContainerVO described previously.

Since we are downloading a file, instead of encoding the response in the VO, I am storing the file in the path and returning the absolute path of the file in response.

Downloading file:

public static HttpResponseContainerVO downloadPDFFile(String url,

String name)

throws ClientProtocolException, IOException {



if (!isExternalStorageAvailable()) {

throw new IOException("External Storage is not Available");
//Use internal storage or Cache or Temp folder to store the files.
}
HttpResponseContainerVO responseVo = new HttpResponseContainerVO();

DefaultHttpClient client = new DefaultHttpClient();


String filePath = getFilePath(name);
HttpGet get = new HttpGet(url);

 
// Add the headers....

HttpResponse response = client.execute(get);

HttpEntity entity = response.getEntity();


responseVo.setResponseCode(response.getStatusLine().getStatusCode());

Header[] headers = response.getAllHeaders();
for (Header hdr : headers) {
//Set the headers
 }


InputStream inputStream = entity.getContent();
FileOutputStream content = new FileOutputStream(new File(filePath));

// Read response into a buffered stream

int readBytes = 0;

byte[] sBuffer = new byte[512];

while ((readBytes = inputStream.read(sBuffer)) != -1) {


content.write(sBuffer, 0, readBytes);

}

content.flush();

content.close();

responseVo.setResponse(filePath);
return responseVo;

}


Getting external file path:

private static String getFilePath(String name) {


String fileDir = Environment.getExternalStorageDirectory()
.getAbsolutePath() +"YOUR DIRECTORY HERE";

String fileName = name + "Extension";

File dir = new File(fileDir);

if (!dir.exists()) {


dir.mkdirs();

}
return fileDir + fileName;


}

Now you have successfully downloaded and stored the file in the external / internal storage. How do you open this file from your app? Simple, follow the code below.


Uri path = Uri.fromFile(new File(VO.getResponse()));

Intent intent = new Intent(Intent.ACTION_VIEW);


intent.setDataAndType(path,
        "MIME TYPE OF THE CONTENT");

intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

try {

startActivity(intent);
} catch (ActivityNotFoundException e) {

Toast.makeText(CONTEXT, MESSAGE,

Toast.LENGTH_LONG).show();


}

 

No comments:

Post a Comment