簡體   English   中英

為什么我的圖片無法從android中的URL下載?

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

我正在嘗試使用URL下載/檢索圖像並將其保存在sdcard 我使用了以下代碼,但是我的圖像文件為空白。 誰能告訴我一步一步做的事情或我哪里做錯了。 我的代碼如下:

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

請查看我的回答,這對我來說是工作。

請在清單文件中提及以下權限

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

請參考此代碼

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

謝謝...... :)如果您有任何問題,請問我...

您為什么不出於自己的目的使用圖像加載庫。 它將以一行代碼從給定的URL加載圖像,並管理所有與圖像加載相關的任務,例如緩存,內存管理,asyn任務等。

例如,只需使用這個很棒的圖像加載庫:

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

只需一行代碼即可完成所有任務

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

您也可以將圖像保存到SD卡中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM