You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ionic 3文件下载至指定目录问题求助

Fixing Ionic 3 File Download: Save to Public Download Folder & Access Issues

Hey there! Let’s work through this file download problem you’re facing with Ionic 3. I’ve dealt with similar headaches before, so here’s a step-by-step breakdown to get your files showing up in the Android Download folder:

Why You Can’t See the File Right Now

The path this.file.dataDirectory points to your app’s private data folder (file:///data/user/0/io.ionic.fileTest/...). Android blocks file managers from accessing this folder by default, which is why you can’t find the downloaded image even though the success alert pops up.

How to Save to Public Download/Documents Folder

To save files to a public, visible directory like Download, you need to handle two key things: storage permissions and valid directory setup. Here’s how to fix your code:

1. Install Required Plugins

First, make sure you have all the necessary Cordova plugins installed (Ionic 3 uses version 4 of Ionic Native packages):

# File transfer plugin
ionic cordova plugin add cordova-plugin-file-transfer
npm install @ionic-native/file-transfer@4

# File system plugin
ionic cordova plugin add cordova-plugin-file
npm install @ionic-native/file@4

# Android permissions plugin (for dynamic permission requests)
ionic cordova plugin add cordova-plugin-android-permissions
npm install @ionic-native/android-permissions@4

Don’t forget to add these plugins to your app.module.ts providers array.

2. Updated Download Code

Replace your existing download() method with this code. It handles permissions, checks for the Download directory, and saves the file correctly:

import { FileTransfer, FileTransferObject } from '@ionic-native/file-transfer';
import { File } from '@ionic-native/file';
import { AndroidPermissions } from '@ionic-native/android-permissions';
import { AlertController } from 'ionic-angular';

constructor(
  private transfer: FileTransfer,
  private file: File,
  private alertCtrl: AlertController,
  private androidPermissions: AndroidPermissions
) {}

async download() {
  // Step 1: Request storage permission (required for Android 6+)
  const permissionStatus = await this.androidPermissions.requestPermission(
    this.androidPermissions.PERMISSION.WRITE_EXTERNAL_STORAGE
  );

  if (permissionStatus.hasPermission) {
    const fileTransfer: FileTransferObject = this.transfer.create();
    const url = "http://cdna.allaboutvision.com/i/conditions-2016/heterochromia-kate-bosworth-660x660-with-credit.jpg";
    // Target public Download folder path
    const targetDir = this.file.externalPublicDirectory + 'Download/';

    try {
      // Step 2: Check if Download directory exists; create it if not
      await this.file.checkDir(this.file.externalPublicDirectory, 'Download');
    } catch (err) {
      await this.file.createDir(this.file.externalPublicDirectory, 'Download', false);
    }

    // Step 3: Start download
    fileTransfer.download(url, targetDir + 'laska.jpg', true).then((entry) => {
      const alertSuccess = this.alertCtrl.create({
        title: `Download Succeeded!`,
        subTitle: `Saved to: ${entry.toURL()}`,
        buttons: ['Ok']
      });
      alertSuccess.present();
    }, (error) => {
      const alertFailure = this.alertCtrl.create({
        title: `Download Failed!`,
        subTitle: `Error code: ${error.code}\nMessage: ${error.message}`,
        buttons: ['Ok']
      });
      alertFailure.present();
    });
  } else {
    // Permission denied alert
    const alertPermission = this.alertCtrl.create({
      title: `Permission Required`,
      subTitle: `We need storage access to save files to your Download folder.`,
      buttons: ['Ok']
    });
    alertPermission.present();
  }
}

3. Key Fixes Explained

  • Permission Handling: Android 6+ requires dynamic permission requests for storage access. Without this, you’ll get permission errors when writing to public folders.
  • Directory Validation: Your earlier error code 1 (FILE_NOT_FOUND) happened because the Download directory might not exist on some devices. The code above checks and creates the directory if needed.
  • Public Path: this.file.externalPublicDirectory points to /storage/emulated/0/ (the root of external storage), so adding Download/ targets the visible public Download folder.

4. Bonus: Fix for window.requestFileSystem Not Working

Ionic Native wraps Cordova’s File API, so you don’t need to use window.requestFileSystem directly. The this.file.checkDir() and this.file.createDir() methods you see in the code are the Ionic-native way to handle file system operations.

5. Android 10+ Scoped Storage Fix

If you’re targeting Android 10 or higher, add these preferences to your config.xml to ensure compatibility with scoped storage:

<preference name="AndroidPersistentFileLocation" value="Compatibility" />
<preference name="AndroidExtraFilesystems" value="files,files-external,documents,sdcard,root" />

内容的提问来源于stack exchange,提问作者bambaniasz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 03:46:16