简体   繁体   中英

Why is my Image not getting downloaded from the URL in android?

I am trying to download / retrieve an image using an URL and saving it in the sdcard . I have used the following codes but my image file is blank. Can anyone tell me what to do step by step or where I am going wrong. My codes are as follows:

  URL url = new URL("http://www.mydomainname.com/task/uploads/test2.png");

  HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();


  urlConnection.setRequestMethod("GET");
  urlConnection.setDoOutput(true); 

  urlConnection.connect();

  File SDCardRoot = Environment.getExternalStorageDirectory();


  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();
 }

Please see my answer it was work for me..

Please mention below permission in your manifest file

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

Please refer this code

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import com.google.android.gms.internal.dw;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Toast;

public class DownLoadImage extends Activity {
    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.action_main);

    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... arg0) {
             Bitmap bitmap = DownloadImage(
                        "http://www.yourdomainname.com/imgs/arrangemen4.jpg");

             String extr = Environment.getExternalStorageDirectory().toString();
                File mFolder = new File(extr + "/MyApp");

                if (!mFolder.exists()) {
                    mFolder.mkdir();
                }

                String strF = mFolder.getAbsolutePath();
                File mSubFolder = new File(strF + "/MyApp-SubFolder");

                if (!mSubFolder.exists()) {
                    mSubFolder.mkdir();
                }

                String s = "myfile.png";

                File f = new File(mSubFolder.getAbsolutePath(),s);

                String strMyImagePath = f.getAbsolutePath();
                 FileOutputStream fos = null;
                 try {
                     fos = new FileOutputStream(f);
                     bitmap.compress(Bitmap.CompressFormat.PNG,70, fos);

                     fos.flush();
                     fos.close();
                  //   MediaStore.Images.Media.insertImage(getContentResolver(), b, "Screen", "screen");
                 }catch (FileNotFoundException e) {

                     e.printStackTrace();
                 } catch (Exception e) {

                     e.printStackTrace();
                 }
            return null;
        }
        protected void onPostExecute(Void result) {
            Toast.makeText(DownLoadImage.this, "Done", Toast.LENGTH_SHORT).show();
        };
    }.execute();
    }

    private InputStream OpenHttpConnection(String urlString) 
            throws IOException
            {
                InputStream in = null;
                int response = -1;

                URL url = new URL(urlString); 
                URLConnection conn = url.openConnection();

                if (!(conn instanceof HttpURLConnection))                     
                    throw new IOException("Not an HTTP connection");

                try{
                    HttpURLConnection httpConn = (HttpURLConnection) conn;
                    httpConn.setAllowUserInteraction(false);
                    httpConn.setInstanceFollowRedirects(true);
                    httpConn.setRequestMethod("GET");
                    httpConn.connect(); 

                    response = httpConn.getResponseCode();                 
                    if (response == HttpURLConnection.HTTP_OK) {
                        in = httpConn.getInputStream();                                 
                    }                     
                }
                catch (Exception ex)
                {
                    throw new IOException("Error connecting");            
                }
                return in;     
            }
            private Bitmap DownloadImage(String URL)
            {        
                Bitmap bitmap = null;
                InputStream in = null;        
                try {
                    in = OpenHttpConnection(URL);
                    bitmap = BitmapFactory.decodeStream(in);
                    in.close();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                return bitmap;                
            }
}

Thank you...... :) if you have any problem please feel to ask me...

Why don't you use a Image Loading Library for your purpose. It will load the image form the given URL in one line of coding and manage all your image loading related task like caching,memory management,asyn task etc.

For example just use the this awesome Image Loading Library:

1.) http://square.github.io/picasso/

It just take one line code to perform all the task

Picasso.with(context)
    .load(url)
    .placeholder(R.drawable.user_placeholder)
    .error(R.drawable.user_placeholder_error)
    .into(imageView);

You can also save a image then to sd card also.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM