Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save image from url to sdcard

Tags:

android

I am saving image from url to sdcard. But image size is 0 in sdcard. Image is created in sdcard but now retrieve data from url and save. so it is giving me 0 size.

try
   {
     URL url = new URL("http://api.androidhive.info/images/sample.jpg");
      InputStream input = url.openStream();
      try {
          //The sdcard directory e.g. '/sdcard' can be used directly, or 
          //more safely abstracted with getExternalStorageDirectory()
          File storagePath = Environment.getExternalStorageDirectory();
          OutputStream output = new FileOutputStream (new File(storagePath,username+".png"));
          try {
              byte[] buffer = new byte[2048];
              int bytesRead = 0;
              while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
                  output.write(buffer, 0, bytesRead);
              }
          } finally {
              output.close();
          }
      } finally {
          input.close();
      }
     } catch(Exception e)
     {
         System.out.println("error in sd card "+e.toString());
     } 
like image 892
user2160008 Avatar asked Mar 25 '23 01:03

user2160008


1 Answers

Try this code.It works...

You should have permission of internet and write external storage.

try
{   
  URL url = new URL("Enter the URL to be downloaded");
  HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
  urlConnection.setRequestMethod("GET");
  urlConnection.setDoOutput(true);                   
  urlConnection.connect();                  
  File SDCardRoot = Environment.getExternalStorageDirectory().getAbsoluteFile();
  String filename="downloadedFile.png";   
  Log.i("Local filename:",""+filename);
  File file = new File(SDCardRoot,filename);
  if(file.createNewFile())
  {
    file.createNewFile();
  }                 
  FileOutputStream fileOutput = new FileOutputStream(file);
  InputStream inputStream = urlConnection.getInputStream();
  int totalSize = urlConnection.getContentLength();
  int downloadedSize = 0;   
  byte[] buffer = new byte[1024];
  int bufferLength = 0;
  while ( (bufferLength = inputStream.read(buffer)) > 0 ) 
  {                 
    fileOutput.write(buffer, 0, bufferLength);                  
    downloadedSize += bufferLength;                 
    Log.i("Progress:","downloadedSize:"+downloadedSize+"totalSize:"+ totalSize) ;
  }             
  fileOutput.close();
  if(downloadedSize==totalSize) filepath=file.getPath();    
} 
catch (MalformedURLException e) 
{
  e.printStackTrace();
} 
catch (IOException e)
{
  filepath=null;
  e.printStackTrace();
}
Log.i("filepath:"," "+filepath) ;
return filepath;
like image 140
Nirav Ranpara Avatar answered Apr 06 '23 04:04

Nirav Ranpara