针对你的需求,uni-app 确实可以通过原生插件来实现对安卓和 iOS 文件及目录的操作。以下是一个简单的示例,展示如何通过原生插件来实现这一功能。
1. 创建原生插件
首先,需要在 native-plugins
目录下创建一个新的原生插件,比如命名为 FileOperation
。
Android 部分
在 FileOperation/android/src/main/java/com/yourcompany/fileoperation/
目录下创建 FileOperationModule.java
:
package com.yourcompany.fileoperation;
import android.content.Context;
import android.os.Environment;
import android.webkit.JavascriptInterface;
import java.io.File;
public class FileOperationModule {
private Context mContext;
FileOperationModule(Context context) {
mContext = context;
}
@JavascriptInterface
public String getExternalStorageDirectory() {
return Environment.getExternalStorageDirectory().getAbsolutePath();
}
@JavascriptInterface
public boolean createFile(String path, String name) {
File file = new File(path, name);
return file.createNewFile();
}
}
在 AndroidManifest.xml
中注册该模块:
<activity android:name="io.dcloud.feature.uniapp.bridge.UniAppJSBridgeActivity"
... >
<intent-filter>
...
</intent-filter>
<meta-data
android:name="android.webkit.JavascriptInterface"
android:value="com.yourcompany.fileoperation.FileOperationModule" />
</activity>
iOS 部分
在 FileOperation/ios/Classes/
目录下创建 FileOperationModule.h
和 FileOperationModule.m
:
// FileOperationModule.h
#import <Foundation/Foundation.h>
#import <JavaScriptCore/JavaScriptCore.h>
@interface FileOperationModule : NSObject <JSExport>
- (NSString *)getExternalStorageDirectory;
- (BOOL)createFileWithPath:(NSString *)path name:(NSString *)name;
@end
// FileOperationModule.m
#import "FileOperationModule.h"
#import <UIKit/UIKit.h>
@implementation FileOperationModule
- (NSString *)getExternalStorageDirectory {
return NSHomeDirectory();
}
- (BOOL)createFileWithPath:(NSString *)path name:(NSString *)name {
NSString *filePath = [path stringByAppendingPathComponent:name];
NSError *error = nil;
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
return !error;
}
@end
2. 在 uni-app 中使用插件
在 manifest.json
中注册插件:
"nativePlugins": {
"FileOperation": {
"package": "com.yourcompany.fileoperation",
"version": "1.0.0",
"provider": "yourcompany"
}
}
在 pages/index/index.vue
中调用插件:
<template>
<view>
<button @click="createFile">Create File</button>
</view>
</template>
<script>
export default {
methods: {
createFile() {
const fileOperation = plus.android.importClass('com.yourcompany.fileoperation.FileOperationModule');
const context = plus.android.runtimeMainActivity();
const module = new fileOperation(context);
// For iOS, use plus.ios to get the module instance
// const module = plus.ios.importClass('FileOperationModule').alloc().init();
const dir = module.getExternalStorageDirectory();
const fileCreated = module.createFile(dir, 'test.txt');
console.log('File created:', fileCreated);
}
}
}
</script>
注意:iOS 部分需通过 plus.ios
导入使用,示例中已注释。实际开发中,需要根据平台判断来调用相应的方法。