开发者

Download a file from webview to a custom folder

Is it possible to download a file to a user defined directory from android webview. Currently the file is being downloaded in SDCard/downloads. Is it possible to override the default download location?

开发者_如何学GoI am currently using the following code to download a file

Intent intent = new Intent(Intent.ACTION_VIEW Uri.parse("download file location"));
startActivity(intent); 


When you mean you need the browser... do you mean you need to handle the download with the browser? Cause you can use the webview and still handle the download yourself.

As @Harry Joy commented, I would use the shouldOverrideUrlLoading(WebView view, String url) method and filter those urls/extensions you want to download separately. If you don't have any specific file extensions or urls you may want to download, but you can edit your html/javascript code maybe you can do some javascript trick to add a flag and make your WebView recognize the url as a download.

To handle the download, maybe you already know, but it would be something like this

    if (sUserAgent == null) {
        Log.e(TAG + " - Conexion", getString(R.string.e_envio_datos));
    }
    // Create client and set our specific user-agent string
    HttpClient client = new DefaultHttpClient();
    HttpPost request = new HttpPost(url);
    request.setHeader("User-Agent", sUserAgent);
    try {
        HttpResponse response = client.execute(request);
        // Check if server response is valid
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() != HTTP_STATUS_OK) {
            // Error
        } else {
            InputStream in = response.getEntity().getContent();
            byte[] read = new byte [1024];
            int numReadBytes= 0, singleByte;
            boolean endFlow= false;
            do {
                singleByte= in.read();
                endFlow = singleByte == -1;
                if (!endFlow) {
                    read[numReadBytes] = (byte) singleByte;
                    numReadBytes++;
                }
            } while (!endFlow);
            if (numReadBytes> 0) {
    // Here you implement some code to store the array of bytes as a file
                storeDataWherever(read);
            }
        }
    } catch (IOException e) {
        Log.e(TAG + " - Conexion", e.getMessage());
    } catch (ArrayIndexOutOfBoundsException e){
        Log.e(TAG + " - Conexion", getString(R.string.e_respuesta_size));       
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜