如何通过android中的url从ftp服务器下载图像/文件?

时间:2017-06-08 09:59:11

标签: java android download

   private String ftpUrl = "ftp://%s:%s@%s/%s;";
   private static String host = "www.krishnas.com.np";
   private static String user = "tryagn@krishnas.com.np";
   private static String pass = "technology_krixnas";
   private static String filePath = "112.jpg";

   private static String savePath = 
   Environment.getExternalStorageDirectory() + "/" + 
   Environment.DIRECTORY_DCIM +"/abe.jpg";

asynctask中的doInBackground()是:

   protected String doInBackground(String... f_url) {
    int count;
    try {

    ftpUrl = String.format(ftpUrl, user, pass, host, filePath);


        //System.out.println("URL: " + ftpUrl)
                Log.d("-----------", ""+ftpUrl);

   //            try {
            //URL url = new URL(ftpUrl);
            //URLConnection conn = url.openConnection();
     //                InputStream inputStream = conn.getInputStream();

        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(savePath);

        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
            i=(int)((total*100)/lenghtOfFile);
            publishProgress(""+(int)((total*100)/lenghtOfFile));

   //                i = (int)((total*100)/lenghtOfFile);

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

        // flushing output
        output.flush();

        // c
        // losing streams
        output.close();
        input.close();

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

    return null;
    }

我想从我的FTP服务器下载文件/图像,它在链接中显示图像但不在内部存储中下载。我正在学习ftp服务器下载器而不是http请求!不知道哪里出错了?

1 个答案:

答案 0 :(得分:0)

您正在使用外部存储来存储文件Environment.getExternalStorageDirectory()

因此,如果您想将其存储在内部存储空间中, 您可以使用getFilesDir()getCacheDir()

File file = new File(context.getFilesDir(), filename);

有关详细信息,请参阅this链接: