ANDROID: How do I download a video file to SD card?

32,377

Solution 1

aren't running out of memory ? I imagine a video file is very large - which you are buffering before writing to file.

I know your example code is all over the internet - but it's BAD for downloading ! Use this:

private final int TIMEOUT_CONNECTION = 5000;//5sec
private final int TIMEOUT_SOCKET = 30000;//30sec


            URL url = new URL(imageURL);
            long startTime = System.currentTimeMillis();
            Log.i(TAG, "image download beginning: "+imageURL);

            //Open a connection to that URL.
            URLConnection ucon = url.openConnection();

            //this timeout affects how long it takes for the app to realize there's a connection problem
            ucon.setReadTimeout(TIMEOUT_CONNECTION);
            ucon.setConnectTimeout(TIMEOUT_SOCKET);


            //Define InputStreams to read from the URLConnection.
            // uses 3KB download buffer
            InputStream is = ucon.getInputStream();
            BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
            FileOutputStream outStream = new FileOutputStream(file);
            byte[] buff = new byte[5 * 1024];

            //Read bytes (and store them) until there is nothing more to read(-1)
            int len;
            while ((len = inStream.read(buff)) != -1)
            {
                outStream.write(buff,0,len);
            }

            //clean up
            outStream.flush();
            outStream.close();
            inStream.close();

            Log.i(TAG, "download completed in "
                    + ((System.currentTimeMillis() - startTime) / 1000)
                    + " sec");5

Solution 2

Never hardwire a path, particularly to external storage. Your path is wrong on many devices. Use Environment.getExternalStoragePath() to get the root of external storage (which may be /sdcard or /mnt/sdcard or something else).

Be sure to create your subdirectory, using the File object you get back from Environment.getExternalStoragePath().

And, finally, don't just say "but its not working". We have no idea what "but its not working" means in your case. Without that information, it is very difficult to help you.

Share:
32,377

Related videos on Youtube

IZI_Shadow_IZI
Author by

IZI_Shadow_IZI

Developer

Updated on July 09, 2022

Comments

  • IZI_Shadow_IZI
    IZI_Shadow_IZI almost 2 years

    I have a video file on a website in .MP4 format and I want to allow the user to be able to download the video to their SD card by clicking a link. Is there an easy way to do this. I currently have this code but its not working...not sure what I am doing wrong. THanks for any help!

    import java.io.BufferedInputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;
    import java.net.URLConnection;
    
    import org.apache.http.util.ByteArrayBuffer;
    
    import android.app.Activity;
    import android.os.Bundle;
    import android.util.Log;
    
    public class VideoManager extends Activity {
     /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);}
    
    
    
            private final String PATH = "/sdcard/download/";  //put the downloaded file here
    
    
            public void DownloadFromUrl(String VideoURL, String fileName) {  //this is the downloader method
                    try {
                            URL url = new URL("http://www.ericmoyer.com/episode1.mp4"); //you can write here any link
                            File file = new File(fileName);
    
                            long startTime = System.currentTimeMillis();
                            Log.d("VideoManager", "download begining");
                            Log.d("VideoManager", "download url:" + url);
                            Log.d("VideoManager", "downloaded file name:" + fileName);
                            /* Open a connection to that URL. */
                            URLConnection ucon = url.openConnection();
    
                            /*
                             * Define InputStreams to read from the URLConnection.
                             */
                            InputStream is = ucon.getInputStream();
                            BufferedInputStream bis = new BufferedInputStream(is);
    
                            /*
                             * Read bytes to the Buffer until there is nothing more to read(-1).
                             */
                            ByteArrayBuffer baf = new ByteArrayBuffer(50);
                            int current = 0;
                            while ((current = bis.read()) != -1) {
                                    baf.append((byte) current);
                            }
    
                            /* Convert the Bytes read to a String. */
                            FileOutputStream fos = new FileOutputStream(PATH+file);
                            fos.write(baf.toByteArray());
                            fos.close();
                            Log.d("VideoManager", "download ready in"
                                            + ((System.currentTimeMillis() - startTime) / 1000)
                                            + " sec");
    
                    } catch (IOException e) {
                            Log.d("VideoManager", "Error: " + e);
                    }
    
            }
    }
    
    • Sameer Segal
      Sameer Segal over 13 years
      Are you sure the path /sdcard/download/ exists? You can create it through adb shell
  • Someone Somewhere
    Someone Somewhere almost 13 years
    added outStream.flush(); this solves the problem of 0 byte files
  • Scorpion
    Scorpion over 11 years
    Is it possible to play the video which is currently downloading? Meaning that let say one.mp4 is currently in downloading state so is it possible to play the same while downloading using MediaPlayer?
  • Dhasneem
    Dhasneem almost 11 years
    @SomeoneSomewhere I am having video in the format of .swf? Will it be download using your code?
  • Someone Somewhere
    Someone Somewhere almost 11 years
    yeah, it will download any file from a URL
  • Kartheek Sarabu
    Kartheek Sarabu about 10 years
    Code works very well but is there any way to download video from the middle. i.e. if there is any internet connection problem it is starting from beginning. How to avoid it.
  • Someone Somewhere
    Someone Somewhere about 10 years
    I have implemented that kind of a feature before... but don't have the source code accessible at the moment. I do remember that the feature depends on the server, i.e. the server must support downloading from a specific byte offset.
  • Rahul Matte
    Rahul Matte almost 10 years
    nice answer I have used code it's error free. it downloads live video stream from url but file is corrupted it is just some kbs
  • Saif Hamed
    Saif Hamed over 9 years
    @SomeoneSomewhere cool, but how i get the file name? header("Content-disposition: attachment; filename=\"" . basename($file_url) . "\"");
  • Someone Somewhere
    Someone Somewhere over 9 years
    I suppose I would do something like url.getPath() and use the text after after the last /