HarmonyOS Next Cross-device File Manager
In today's era when digital office work and life are becoming increasingly popular, the demand for multi-device collaborative file processing is growing stronger. This article will delve into how to develop a cross-device file manager based on HarmonyOS Next. It enables users to freely drag and drop files between mobile phones, tablets, and PCs, achieving rapid synchronization and distribution, and significantly improving file management efficiency.
Technical Architecture Design for Cross-device File Management
Core Functions
- File Drag-and-drop: Allows users to directly drag and drop files between different devices, breaking the physical boundaries between devices and enabling convenient file transfer.
- Automatic Synchronization: Ensures that files are updated in real-time across different devices. No matter which device a file is modified on, other devices can synchronize the changes promptly.
- Permission Management: Strictly controls the access and transmission permissions of files to prevent files from being accessed or modified by unauthorized devices.
- Resumable File Transfer: In the process of transferring large files, if there is a network interruption or other abnormal situations, the transfer can resume from the breakpoint, avoiding the need to start over.
Design of Cross-device Drag-and-drop (draggable=true + onDrop)
By setting the draggable attribute of a component to true, files can be made draggable. When a user starts to drag a file, the onDragStart event is triggered. In this event, the file data to be transferred can be set. The onDrop event is used to process the received file data on the target device, enabling the reception and storage of the file.
Using Distributed File APIs for Intelligent Storage (Distributed Data Objects)
The distributed data objects in the distributed file APIs provided by HarmonyOS Next offer powerful support for file storage and synchronization. Distributed data objects can automatically manage the storage and synchronization of files across different devices, ensuring data consistency and integrity.
Implementing Drag-and-drop File Management
Using onDragStart() to Enable File Dragging from PC to Mobile Phone
The following is a simple code example showing how to make a file draggable on the PC side:
import { DragEvent } from '@ohos.arkui';
// Assume this is a file component
FileComponent()
.draggable(true)
.onDragStart((event: DragEvent) => {
// Get the file data. Here, assume getFileData() is a method to get the binary data of the file
let fileData = getFileData();
// Set the file data to be transferred
event.data.setData('application/octet-stream', fileData);
})
Using onDrop() to Automatically Create a File Copy on the Target Device
On the mobile phone side, use the onDrop event to process the received file data and create a file copy:
import { DropEvent } from '@ohos.arkui';
import fs from '@ohos.file.fs';
// Assume this is a file reception area component
FileDropArea()
.onDrop((event: DropEvent) => {
let data = event.data;
let fileData = data.getPrimaryData();
if (fileData) {
// Generate a file name. This is a simple example and can be adjusted according to actual needs
let fileName = 'transferred_file.dat';
// Save the file locally
fs.writeFile({
path: fileName,
data: fileData,
encoding: 'binary',
success: () => {
console.log('File saved successfully');
},
fail: (err) => {
console.error(`Failed to save the file. Error code: ${err.code}, error message: ${err.message}`);
}
});
}
})
Combining SystemPasteboard to Support Cross-device Paste Operations (Dual Channels of Drag-and-drop and Copy)
In addition to the drag-and-drop function, the system pasteboard can be combined to implement cross-device paste operations. The following is a simple example:
import pasteboard from '@ohos.pasteboard';
import { BusinessError } from '@ohos.base';
// Copy file data to the clipboard
export async function copyFileToClipboard(fileData: Uint8Array): Promise<void> {
let pasteData: pasteboard.PasteData = pasteboard.createData('application/octet-stream', fileData);
let systemPasteBoard: pasteboard.SystemPasteboard = pasteboard.getSystemPasteboard();
await systemPasteBoard.setData(pasteData).catch((err: BusinessError) => {
console.error(`Failed to set pastedata. Code: ${err.code}, message: ${err.message}`);
});
}
// Get file data from the clipboard
export async function getFileFromClipboard(): Promise<Uint8Array | null> {
let systemPasteBoard: pasteboard.SystemPasteboard = pasteboard.getSystemPasteboard();
return new Promise((resolve, reject) => {
systemPasteBoard.getData((err: BusinessError, data: pasteboard.PasteData) => {
if (err) {
console.error(`Failed to get pastedata. Code: ${err.code}, message: ${err.message}`);
resolve(null);
} else {
let fileData = data.getPrimaryData();
resolve(fileData);
}
});
});
}
Improving the Stability and Security of Data Transmission
Using distributedDataObject.save() to Ensure Data Integrity
During the file transfer process, using the save() method of the distributed data object can ensure data integrity. This method automatically handles data storage and synchronization, guaranteeing file consistency across different devices.
import { DistributedDataObject } from '@ohos.data.distributedDataObject';
// Create a distributed data object
let ddo = new DistributedDataObject();
// Assume fileData is the file data to be saved
ddo.setData('fileData', fileData);
// Save the data
ddo.save().then(() => {
console.log('Data saved successfully');
}).catch((err) => {
console.error(`Failed to save the data. Error code: ${err.code}, error message: ${err.message}`);
});
Resumable File Transfer Mechanism: How to Ensure Uninterrupted Transfer of Large Files
To implement resumable file transfer, the progress of the file transfer needs to be recorded. The number of bytes already transferred can be recorded each time data is transferred. When the transfer is interrupted and restarted, the transfer resumes from the breakpoint. The following is a simple example:
import fs from '@ohos.file.fs';
import { BusinessError } from '@ohos.base';
// Assume fileData is the file data to be transferred and offset is the number of bytes already transferred
export async function resumeFileTransfer(fileData: Uint8Array, offset: number): Promise<void> {
let remainingData = fileData.slice(offset);
fs.writeFile({
path: 'transferred_file.dat',
data: remainingData,
encoding: 'binary',
position: offset,
success: () => {
console.log('File transfer resumed successfully');
},
fail: (err: BusinessError) => {
console.error(`Failed to resume the file transfer. Error code: ${err.code}, error message: ${err.message}`);
}
});
}
Permission Control: How to Prevent Unauthorized File Transfer to Other Devices
To prevent unauthorized file transfer to other devices, strict permission control is required. When the application is launched, the user can be asked to grant necessary permissions, such as file access permissions and cross-device transfer permissions. During the file transfer process, device authentication can be performed to ensure that only authorized devices can receive files.
import abilityAccessCtrl from '@ohos.abilityAccessCtrl';
import systemPermission from '@ohos.security.systemPermission';
// Check permissions
async function checkPermission(): Promise<boolean> {
let atManager = abilityAccessCtrl.createAtManager();
let result = await atManager.verifyPermissionFromSelf(systemPermission.DISTRIBUTED_DATASYNC);
return result === abilityAccessCtrl.PermissionState.PERMISSION_GRANTED;
}
// Request permissions
async function requestPermission(): Promise<boolean> {
let atManager = abilityAccessCtrl.createAtManager();
let result = await atManager.requestPermissionsFromUser([systemPermission.DISTRIBUTED_DATASYNC]);
return result.authResults[0] === abilityAccessCtrl.PermissionState.PERMISSION_GRANTED;
}
Through the above technical architecture design and implementation solutions, we can develop a powerful, stable, and secure cross-device file manager, providing users with a convenient and efficient file management experience.
Top comments (0)