简体   繁体   English

为什么我的图片无法从android中的URL下载?

[英]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 . 我正在尝试使用URL下载/检索图像并将其保存在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. 它将以一行代码从给定的URL加载图像,并管理所有与图像加载相关的任务,例如缓存,内存管理,asyn任务等。

For example just use the this awesome Image Loading Library: 例如,只需使用这个很棒的图像加载库:

1.) http://square.github.io/picasso/ 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. 您也可以将图像保存到SD卡中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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