Skip to content

文件

免费插件

此插件免费开源,采用 MIT 许可证。

概述

File API 提供跨平台的文件操作功能。

安装

shell
composer require nativephp/mobile-file

使用

PHP (Livewire/Blade)

php
use Native\Mobile\Facades\File;

// 移动文件
$result = File::move('/path/to/source.txt', '/path/to/destination.txt');

if ($result['success']) {
    echo '文件移动成功!';
}

// 复制文件
$result = File::copy('/path/to/source.txt', '/path/to/copy.txt');

if ($result['success']) {
    echo '文件复制成功!';
}

JavaScript (Vue/React/Inertia)

js
import { file } from '#nativephp';

// 移动文件
const result = await file.move('/path/to/source.txt', '/path/to/destination.txt');

if (result.success) {
    console.log('文件移动成功!');
}

// 复制文件
const result = await file.copy('/path/to/source.txt', '/path/to/copy.txt');

if (result.success) {
    console.log('文件复制成功!');
}

方法

move(string $from, string $to): array

将文件从源位置移动到目标位置。

参数类型描述
fromstring源文件路径
tostring目标文件路径

返回:

  • success: bool - 操作是否成功
  • error: string - 操作失败时的错误信息(可选)

copy(string $from, string $to): array

将文件从源位置复制到目标位置。

参数类型描述
fromstring源文件路径
tostring目标文件路径

返回:

  • success: bool - 操作是否成功
  • error: string - 操作失败时的错误信息(可选)

行为

  • 如果父目录不存在,会自动创建
  • 目标位置的现有文件会被覆盖
  • 复制操作后会验证文件完整性
  • 在 Android 上,如果重命名失败(跨文件系统),会回退到复制+删除

示例

移动文件到永久存储

php
use Native\Mobile\Facades\File;

$tempPath = '/var/mobile/Containers/Data/tmp/recording.m4a';
$permanentPath = storage_path('recordings/recording.m4a');

$result = File::move($tempPath, $permanentPath);

if ($result['success']) {
    // 文件移动成功
}

编辑前备份文件

php
use Native\Mobile\Facades\File;

public function editFile($filePath)
{
    // 创建备份
    $backupPath = str_replace('.txt', '_backup.txt', $filePath);
    File::copy($filePath, $backupPath);

    // 继续编辑...
}

基于 NativePHP 官方文档翻译