简体   繁体   English

如何将所有文件从服务器下载到SD卡

[英]How to download all files from server to SD-card

I have several files uploaded to my server , now what i am trying to do is i want to download all files one by one and save it in to one folder. 我有几个文件上传到我的服务器,现在我想做的是我要一个一个地下载所有文件并将其保存到一个文件夹中。

So basically i was trying to do something like [this][1] but some how i am not able to achieve this so i think an alternate way to do it. 所以基本上我试图做类似[this] [1]的事情,但是我却无法做到这一点,所以我认为这是另一种方法。 So i am planning to download all audio file of particular folder of server to my SD-card folder and then i will give path of SD-card to list-view and play that audio. 所以我打算将服务器特定文件夹的所有音频文件下载到我的SD卡文件夹中,然后我将SD卡的路径提供给列表视图并播放该音频。

So basically my question is how can i download all file from server folder to my SD-card folder. 所以基本上我的问题是我如何将所有文件从服务器文件夹下载到我的SD卡文件夹中。

I have below piece of code which is working fine for single file. 我有下面的一段代码,它对单个文件工作正常。

public class ServerFileList extends Activity {

    Uri uri;
    URL urlAudio;
    ListView mListView;
    ProgressDialog pDialog;
    private MediaPlayer mp = new MediaPlayer();
    private List<String> myList = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.serverfilelist);

        mListView = (ListView) findViewById(R.id.listAudio);
        // new getAudiofromServer().execute();
        new downloadAudio().execute();

        mListView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                playSong(urlAudio + myList.get(position));
            }
        });
    }

    public void updateProgress(int currentSize, int totalSize) {
        TextView mTextView = new TextView(ServerFileList.this);
        mTextView.setText(Long.toString((currentSize / totalSize) * 100) + "%");
    }

    private void playSong(String songPath) {
        try {
            mp.reset();
            mp.setDataSource(songPath);
            mp.prepare();
            mp.start();
        } catch (IOException e) {
            Log.v(getString(R.string.app_name), e.getMessage());
        }
    }

    class downloadAudio extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ServerFileList.this);
            pDialog.setMessage("Downloading File list from server, Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... arg0) {

            // set the download URL, a url that points to a file on the internet
            // this is the file to be downloaded
            URL url = null;
            try {
                url = new URL("http://server/folder/uploadAudio/abcd.mp3");
            } catch (MalformedURLException e3) {
                // TODO Auto-generated catch block
                e3.printStackTrace();
            }

            // create the new connection
            HttpURLConnection urlConnection = null;
            try {
                urlConnection = (HttpURLConnection) url.openConnection();
            } catch (IOException e5) {
                // TODO Auto-generated catch block
                e5.printStackTrace();
            }

            // set up some things on the connection
            try {
                urlConnection.setRequestMethod("GET");
            } catch (ProtocolException e4) {
                // TODO Auto-generated catch block
                e4.printStackTrace();
            }
            urlConnection.setDoOutput(true);

            // and connect!
            try {
                urlConnection.connect();
            } catch (IOException e3) {
                // TODO Auto-generated catch block
                e3.printStackTrace();
            }

            // set the path where we want to save the file
            // in this case, going to save it on the root directory of the
            // sd card.
            String MEDIA_PATH = new String(
                    Environment.getExternalStorageDirectory()
                            + "/newDirectory/");
            File SDCardRoot = new File(MEDIA_PATH);

            if (!SDCardRoot.exists()) {
                SDCardRoot.mkdir();
            }
            // create a new file, specifying the path, and the filename
            // which we want to save the file as.
            File file = new File(SDCardRoot, System.currentTimeMillis()
                    + ".mp3");

            // this will be used to write the downloaded data into the file we
            // created
            FileOutputStream fileOutput = null;
            try {
                fileOutput = new FileOutputStream(file);
            } catch (FileNotFoundException e2) {
                // TODO Auto-generated catch block
                e2.printStackTrace();
            }

            // this will be used in reading the data from the internet
            InputStream inputStream = null;
            try {
                inputStream = urlConnection.getInputStream();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            // this is the total size of the file
            int totalSize = urlConnection.getContentLength();
            // variable to store total downloaded bytes
            int downloadedSize = 0;

            // create a buffer...
            byte[] buffer = new byte[1024];
            int bufferLength = 0; // used to store a temporary size of the
                                    // buffer

            // now, read through the input buffer and write the contents to the
            // file
            try {
                while ((bufferLength = inputStream.read(buffer)) > 0) {
                    // add the data in the buffer to the file in the file output
                    // stream (the file on the sd card
                    fileOutput.write(buffer, 0, bufferLength);
                    // add up the size so we know how much is downloaded
                    downloadedSize += bufferLength;
                    // this is where you would do something to report the
                    // prgress,
                    // like this maybe
                    updateProgress(downloadedSize, totalSize);

                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            // close the output stream when done
            try {
                fileOutput.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;

            // catch some possible errors...

        }

        protected void onPostExecute(String file_url) {
            if (pDialog.isShowing()) {
                pDialog.dismiss();
            }
        }
    }

    class getAudiofromServer extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ServerFileList.this);
            pDialog.setMessage("Getting File list from server, Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @SuppressWarnings("unchecked")
        @Override
        protected String doInBackground(String... arg0) {
            try {
                urlAudio = new URL("http://server/folder/uploadAudio");
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
            ApacheURLLister lister1 = new ApacheURLLister();
            try {
                myList = lister1.listAll(urlAudio);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        protected void onPostExecute(String file_url) {
            if (pDialog.isShowing()) {
                pDialog.dismiss();
            }

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                    ServerFileList.this, android.R.layout.simple_list_item_1,
                    myList);
            adapter.notifyDataSetChanged();
            mListView.setAdapter(adapter);
            mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
            mListView.setCacheColorHint(Color.TRANSPARENT);
        }
    }
     }

Try follow steps, 尝试按照以下步骤操作,

  1. Write a server side component which will return back the list of the files in the directory in which all the audio files are hosted. 编写一个服务器端组件,该组件将返回托管所有音频文件的目录中的文件列表。

  2. In your downloadAudio class, instead of downloading a file, initially make a call to the component described above to get the list. 在您的downloadAudio类中,首先下载上述组件以获取列表,而不是下载文件。

  3. Move the code which you have written in an function which will take String argument. 移动您在带有String参数的函数中编写的代码。

  4. Loop on the url list from step 2 and call function in step 3 with parameter as current element of url list. 从第2步循环到url列表,并在第3步以参数作为url列表的当前元素调用函数。

  5. Keep all checks and balances to ensure all the files are downloaded. 保持所有检查和平衡,以确保下载了所有文件。

Your issue is more of design issue then programming. 您的问题更多的是设计问题,然后是编程。

I have solved the problem by adding ivy jar file as a library and then added following code. 我已经通过添加常春藤jar文件作为库解决了问题,然后添加了以下代码。

        try {
            urlAudio = new URL("http://server/folder/uploadAudio");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        ApacheURLLister lister1 = new ApacheURLLister();
        try {
            myList = lister1.listAll(urlAudio);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM