Kostya Khuta
Kostya Khuta

Reputation: 1856

Download docx file from url android

i want to download file from url. http://opengov.dev.ifabrika.ru/upload/435/IF_Заявка_Программист PHP_2013-09-03.docx - you can try it, it work. My code is next:

 new DownloadFileFromURL().execute("http://opengov.dev.ifabrika.ru/upload/435/IF_Заявка_Программист PHP_2013-09-03.docx");

DownloadFileFromUrl is

 class DownloadFileFromURL extends AsyncTask<String, String, String> {
    private ProgressDialog pDialog;
    public static final int progress_bar_type = 0;

    /**
     * Before starting background thread Show Progress Bar Dialog
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(PostInfoActivity.this);
        pDialog.setMessage("Downloading file. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setMax(100);
        pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    /**
     * Downloading file in background thread
     */
    @Override
    protected String doInBackground(String... f_url) {
        int count;
        try {
            URL url = new URL(f_url[0]);
            URLConnection conection = url.openConnection();
            conection.connect();

            // this will be useful so that you can show a tipical 0-100%
            // progress bar
            int lenghtOfFile = conection.getContentLength();

            // download the file
            InputStream input = new BufferedInputStream(url.openStream(),
                    8192);

            // Output stream
            OutputStream output = new FileOutputStream(Environment
                    .getExternalStorageDirectory().toString()
                    + "/test.docx");

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                // After this onProgressUpdate will be called
                publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                // writing data to file
                output.write(data, 0, count);
            }

            // flushing output
            output.flush();

            // closing streams
            output.close();
            input.close();

        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }

        return null;
    }

    /**
     * Updating progress bar
     */
    protected void onProgressUpdate(String... progress) {
        // setting progress percentage
        pDialog.setProgress(Integer.parseInt(progress[0]));
    }

    /**
     * After completing background task Dismiss the progress dialog
     * *
     */
    @Override
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after the file was downloaded
        if (pDialog != null) {
            pDialog.dismiss();
        }
    }

}

After this a saw new test.docx file in my root folder, but its size is 26 byte and i can not open it.

Upvotes: 1

Views: 544

Answers (4)

Toppers
Toppers

Reputation: 549

Hey I have checked your link which you got after encoding...The Problem here is the + character which replaced the white space http://opengov.dev.ifabrika.ru/upload/435/IF_Заявка_Программист+PHP_2013-09-03.docx.....TO resolve this issue replace your + character with %20 and then try....This will definitely work... and you can also do that before encoding i.e replace your white space with %20...so the final link should be like http://opengov.dev.ifabrika.ru/upload/435/IF_Заявка_Программист%20PHP_2013-09-03.docx

Upvotes: 0

Jayesh Khasatiya
Jayesh Khasatiya

Reputation: 2140

I think Problem is you used only URLConnection class instead of HttpUrlConnection class. refer below link Download a file with Android, and showing the progress in a ProgressDialog

Upvotes: 0

Syamantak Basu
Syamantak Basu

Reputation: 935

You can try with this method by calling this method from your doInBackground

private void downloader(String urlstr) {
    HttpURLConnection c = null;
    FileInputStream fis = null;
    FileOutputStream fbo = null;
    File file = null, file1;
    File outputFile = null;
    InputStream is = null;
    URL url = null;

    try {
        outputFile = new File(Environment
                .getExternalStorageDirectory().toString()
                + "/test.docx");
        if(outputFile.exists())
            Log.e("File delete",outputFile.delete()+"");
        fbo = new FileOutputStream(outputFile, false);

        // connect with server where remote file is stored to download it
        url = new URL(urlstr);
        c = (HttpURLConnection) url.openConnection();
        c.setRequestMethod("GET");
        c.setDoOutput(true);
        c.setConnectTimeout(0);

        c.connect();

        is = c.getInputStream();

        byte[] buffer = new byte[1024];
        int len1 = 0;
        while ((len1 = is.read(buffer)) != -1) {
            fbo.write(buffer, 0, len1);
            Log.e("length", len1+"----");
        }

        fbo.flush();

    } catch (Exception e) {

    } finally {

        if (c != null)
            c.disconnect();
        if (fbo != null)
            try {
                fbo.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        if (is != null)
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        file = null;
        outputFile = null;

    }

}

Upvotes: 0

Toppers
Toppers

Reputation: 549

This happening because your url is in unicoded form so you have to first encode it then try to download

        URLEncoder.encode(Url, "UTF-8")

It works for me.

Upvotes: 1

Related Questions