繁体   English   中英

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

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

我有几个文件上传到我的服务器,现在我想做的是我要一个一个地下载所有文件并将其保存到一个文件夹中。

所以基本上我试图做类似[this] [1]的事情,但是我却无法做到这一点,所以我认为这是另一种方法。 所以我打算将服务器特定文件夹的所有音频文件下载到我的SD卡文件夹中,然后我将SD卡的路径提供给列表视图并播放该音频。

所以基本上我的问题是我如何将所有文件从服务器文件夹下载到我的SD卡文件夹中。

我有下面的一段代码,它对单个文件工作正常。

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);
        }
    }
     }

尝试按照以下步骤操作,

  1. 编写一个服务器端组件,该组件将返回托管所有音频文件的目录中的文件列表。

  2. 在您的downloadAudio类中,首先下载上述组件以获取列表,而不是下载文件。

  3. 移动您在带有String参数的函数中编写的代码。

  4. 从第2步循环到url列表,并在第3步以参数作为url列表的当前元素调用函数。

  5. 保持所有检查和平衡,以确保下载了所有文件。

您的问题更多的是设计问题,然后是编程。

我已经通过添加常春藤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