如何识别文件是否存在于我的webserver文件夹中或不存在于android中

时间:2014-03-05 13:05:29

标签: android webserver

背景:

我有一个典型的要求,即在Android上显示来自Web服务器的一些图像。网络服务器中的所有图像都按顺序编号,我现在可以在android中显示图片。

问题: 是否可以识别网络服务器中是否存在图像?如果没有图像,那么我没有得到图像,也没有向我显示错误

代码:

公共类ImageViewFromURLActivity扩展了Activity {

public static final String URL =
    "http://mywebsite.com/private/image1.jpg";  //this is just an example
ImageView imageView;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    imageView = (ImageView) findViewById(R.id.imageView);

    // Create an object for subclass of AsyncTask
    GetXMLTask task = new GetXMLTask();
    // Execute the task
    task.execute(new String[] { URL });
}

private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
    @Override
    protected Bitmap doInBackground(String... urls) {
        Bitmap map = null;
        for (String url : urls) {
            map = downloadImage(url);
        }
        return map;
    }

    // Sets the Bitmap returned by doInBackground
    @Override
    protected void onPostExecute(Bitmap result) {
        imageView.setImageBitmap(result);
    }

    // Creates Bitmap from InputStream and returns it
    private Bitmap downloadImage(String url) {
        Bitmap bitmap = null;
        InputStream stream = null;
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inSampleSize = 1;

        try {
            stream = getHttpConnection(url);
            bitmap = BitmapFactory.
                    decodeStream(stream, null, bmOptions);
            stream.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return bitmap;
    }

    // Makes HttpURLConnection and returns InputStream
    private InputStream getHttpConnection(String urlString)
            throws IOException {
        InputStream stream = null;
        URL url = new URL(urlString);
        URLConnection connection = url.openConnection();

        try {
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            httpConnection.setRequestMethod("GET");
            httpConnection.connect();

            if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                stream = httpConnection.getInputStream();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return stream;
    }
}

}

1 个答案:

答案 0 :(得分:0)

您可以使用JavaScript和Image.onload事件来确定是否可以加载图片。

示例:

var img = new Image;
img.onerror = function() {
  // you can also do something in the error event handler
}
img.onload = function() {
  // display the image via JS here.
}
img.src = 'path/to/file';