【问题标题】:Error while download url file to internal storage in android?将url文件下载到android内部存储时出错?
【发布时间】:2017-08-10 05:56:03
【问题描述】:

朋友们好! 我只是想将图像从 url 下载到内部存储 http://github.com/google/fonts/blob/master/apache/roboto/Roboto-Regular.ttf?raw=true。我已经创建了目录。

        try
        {
        File folder = new File(getFilesDir() + "/"+"SS");
        if (!folder.exists())
        {
        folder.mkdir();
        Log.i("Directory","Created");
        }
        //URL connection 
        URL url = new URL(fonturl);
        HttpURLConnection c = (HttpURLConnection) 
        url.openConnection();
        c.connect();
        File apkStorage=new File(getFilesDir().getPath());
        Log.i("ApkStorage",""+apkStorage);
       outputFile=new File(apkStorage.getAbsolutePath() +"/");
            if(!outputFile.exists())
            {
            try {
                outputFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Log.e("FIle", "File Created");
        }
        FileOutputStream fos = new FileOutputStream(outputFile);
        InputStream is = c.getInputStream();
        byte[] buffer = new byte[1024];
        int len1 = 0;
        while ((len1 = is.read(buffer)) != -1) {
            fos.write(buffer, 0, len1);
        }
        fos.close();
        is.close();
        }
        catch (Exception e) {
        e.printStackTrace();
        outputFile = null;
        Log.e("Error", "Download Error Exception " + e.getMessage());
        }
        }

它只是创建我指定的文件名 download.jpg 不将文件从 url 下载到内部存储。

错误:未在我的目录中下载字体显示类似这样的错误 Download Error Exception /data/user/0/sdk.nfnlabs.in.customfonts/files(是一个目录)。它应该直接下载到我的目录,如roboto.tff,而不提供文件名。

【问题讨论】:

  • 您可以与问题分享什么错误
  • 请分享错误日志
  • 请帮我解决我的错误
  • 可能outputFile=new File(apkStorage.getAbsolutePath() +"/"); 是错误.. 它应该是outputFile=new File(apkStorage.getAbsolutePath() +"/filename.ttf");
  • 是的,我也试过了。如果我把 robots.ttf 它只是创建文件但我需要文件必须下载

标签: android download


【解决方案1】:

您可以使用以下功能

public void downloadFile(Context context){

    public long enqueue;
    public DownloadManager dm;

    dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    DownloadManager.Request request = new DownloadManager.Request(
            Uri.parse("http://github.com/google/fonts/blob/master/apache/roboto/Roboto-Regular.ttf?raw=true"));
    File direct = new File(Environment.getExternalStorageDirectory()
            + "/SS");

    if (!direct.exists()) {
        direct.mkdirs();
    }
    request.setAllowedNetworkTypes(
            DownloadManager.Request.NETWORK_WIFI
                    | DownloadManager.Request.NETWORK_MOBILE)
            .setAllowedOverRoaming(false).setTitle("Downloading...")
            .setDescription("Please wait. File is downloading...")
            .setDestinationInExternalPublicDir("/SS","Roboto-Regular.ttf")
            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

    enqueue = dm.enqueue(request);



    context.registerReceiver(receiver, new IntentFilter(
            DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}

广播接收器类用于知道天气下载是否完成。

public BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();
        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {

            File direct = new File(Environment.getExternalStorageDirectory()
                    + "/SS");
            Toast.makeText(context,"File saved at location : "+direct.getAbsolutePath(),Toast.LENGTH_SHORT).show();

            context.unregisterReceiver(receiver);
            Activity_Downloads.callDownloadWS(context);

            long downloadId = intent.getLongExtra(
                    DownloadManager.EXTRA_DOWNLOAD_ID, 0);
            DownloadManager.Query query = new DownloadManager.Query();
            query.setFilterById(enqueue);
            Cursor c = dm.query(query);
            if (c.moveToFirst()) {
                int columnIndex = c
                        .getColumnIndex(DownloadManager.COLUMN_STATUS);
                if (DownloadManager.STATUS_SUCCESSFUL == c
                        .getInt(columnIndex)) {

                }
            }
        }
    }
};

别忘了添加

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

【讨论】:

    【解决方案2】:

    您可以从HttpUrlConnection 获取文件名,如下所示

    HttpURLConnection c = (HttpURLConnection) url.openConnection();
    c.connect();
    File apkStorage = new File(getFilesDir().getPath());
    Log.i("ApkStorage",""+apkStorage);
    String raw = c.getHeaderField("Content-Disposition");
    // raw = "attachment; filename=Roboto-Regular.ttf"
    String fileName;
    if(raw != null && raw.indexOf("=") != -1) {
        fileName = raw.split("=")[1]; //getting value after '='
    } else {
        // fall back to random generated file name?
        fileName = "unknown_file";
    }
    outputFile = new File(apkStorage, fileName);
    

    希望对你有所帮助。

    【讨论】:

      猜你喜欢
      • 2012-11-30
      • 1970-01-01
      • 2017-07-12
      • 2014-05-31
      • 2017-12-05
      • 1970-01-01
      • 2023-03-10
      • 2014-04-25
      • 2011-10-10
      相关资源
      最近更新 更多