1# Copying Files Across Devices 2<!--Kit: Core File Kit--> 3<!--Subsystem: FileManagement--> 4<!--Owner: @wang_zhangjun; @zhuangzhuang--> 5<!--Designer: @wang_zhangjun; @zhuangzhuang; @renguang1116--> 6<!--Tester: @liuhonggang123; @yue-ye2; @juxiaopang--> 7<!--Adviser: @foryourself--> 8 9The distributed file system provides the cross-device file copy capability for applications. You can use [@ohos.file.fs](../reference/apis-core-file-kit/js-apis-file-fs.md) to copy files across devices and applications. This topic walks you through the process of copying a file from device A to device B. 10 11## How to Develop 12 131. Connect the devices to form a Super Device.<br> 14 Log in to the same account on two devices and ensure that Bluetooth and Wi-Fi are enabled. Bluetooth does not need to be connected, and Wi-Fi does not need to be connected to the same LAN. 15 162. Grant the distributed data synchronization permission. 17 Use **requestPermissionsFromUser** to request user authorization for the ohos.permission.DISTRIBUTED_DATASYNC permission in the form of a dialog box. For details about how to obtain the application context, see [Obtaining the Context of UIAbility](../application-models/uiability-usage.md#obtaining-the-context-of-uiability). 18 19 ```ts 20 import { common, abilityAccessCtrl } from '@kit.AbilityKit'; 21 import { BusinessError } from '@kit.BasicServicesKit'; 22 // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. 23 let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 24 let atManager = abilityAccessCtrl.createAtManager(); 25 try { 26 // Request the permission from users in the form of a dialog box. 27 atManager.requestPermissionsFromUser(context, ['ohos.permission.DISTRIBUTED_DATASYNC']).then((result) => { 28 console.info(`Request permission result: ${JSON.stringify(result)}`); 29 }).catch((err: BusinessError) => { 30 console.error(`Failed to request permissions from user. Code: ${err.code}, message: ${err.message}`); 31 }) 32 } catch (error) { 33 let err: BusinessError = error as BusinessError; 34 console.error(`Catch err. Failed to request permissions from user. Code: ${err.code}, message: ${err.message}`); 35 } 36 ``` 37 383. Copy files across devices. 39 Place the files in the **distributedfiles/** directory of the application sandbox directory to implement file copy from difference devices. 40 41 Copy the file of device A from the sandbox directory to the **distributedfiles/** directory of device A. 42 43 ```ts 44 import { fileIo as fs } from '@kit.CoreFileKit'; 45 import { common } from '@kit.AbilityKit'; 46 import { BusinessError } from '@kit.BasicServicesKit'; 47 import { fileUri } from '@kit.CoreFileKit'; 48 49 // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. 50 let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 51 let pathDir: string = context.filesDir; 52 let distributedPathDir: string = context.distributedFilesDir; 53 // Sandbox directory of the file to copy. 54 let filePath: string = pathDir + '/src.txt'; 55 try { 56 // Sandbox file to copy. 57 let file = fs.openSync(filePath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE); 58 fs.writeSync(file.fd, 'Create file success'); 59 fs.closeSync(file); 60 } catch (error) { 61 console.error(`Failed to createFile. Code: ${error.code}, message: ${error.message}`); 62 } 63 64 // Obtain the URI of the file to copy. 65 let srcUri = fileUri.getUriFromPath(filePath); 66 // Obtain the URI of the destination path (distributed file directory). 67 let destUri: string = fileUri.getUriFromPath(distributedPathDir + '/src.txt'); 68 try { 69 // Copy the file from the sandbox directory to the distributed file directory. 70 fs.copy(srcUri, destUri).then(()=>{ 71 console.info(`Succeeded in copying---. `); 72 console.info(`src: ${srcUri} dest: ${destUri}`); 73 }).catch((error: BusinessError)=>{ 74 let err: BusinessError = error as BusinessError; 75 console.error(`Failed to copy. Code: ${err.code}, message: ${err.message}`); 76 }) 77 } catch (error) { 78 console.error(`Catch err. Failed to copy. Code: ${error.code}, message: ${error.message}`); 79 } 80 ``` 81 82 Device B copies the file from the distributed file directory of device B. 83 84 ```ts 85 import { fileIo as fs } from '@kit.CoreFileKit'; 86 import { common } from '@kit.AbilityKit'; 87 import { BusinessError } from '@kit.BasicServicesKit'; 88 import { fileUri } from '@kit.CoreFileKit'; 89 import { distributedDeviceManager } from '@kit.DistributedServiceKit'; 90 91 // The context is passed from EntryAbility. Ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. 92 let context = this.getUIContext().getHostContext() as common.UIAbilityContext; 93 let pathDir: string = context.filesDir; 94 let distributedPathDir: string = context.distributedFilesDir; 95 // Destination path (sandbox directory) to which the file is to be copied. 96 let destPath: string = pathDir + '/dest.txt'; 97 // Obtain the URI of the destination path. 98 let destUri = fileUri.getUriFromPath(destPath); 99 100 // Copy the source file path (distributed file directory). 101 let srcPath = distributedPathDir + '/src.txt'; 102 // Obtain the URI of the source path. 103 let srcUri: string = fileUri.getUriFromPath(srcPath); 104 105 // Define a callback for the file copy operation. 106 let progressListener: fs.ProgressListener = (progress: fs.Progress) => { 107 console.info(`progressSize: ${progress.processedSize}, totalSize: ${progress.totalSize}`); 108 }; 109 let options: fs.CopyOptions = { 110 "progressListener" : progressListener 111 }; 112 // Obtain the network ID of device A by calling distributed device management APIs. 113 let dmInstance = distributedDeviceManager.createDeviceManager("com.example.hap"); 114 let deviceInfoList: Array<distributedDeviceManager.DeviceBasicInfo> = dmInstance.getAvailableDeviceListSync(); 115 if (deviceInfoList && deviceInfoList.length > 0) { 116 console.info(`success to get available device list`); 117 let networkId = deviceInfoList[0].networkId; // Only two devices are connected. The first element in the list is the network ID of device A. 118 // Define the callback for accessing the distributed file directory. 119 let listeners : fs.DfsListeners = { 120 onStatus: (networkId: string, status: number): void => { 121 console.error(`Failed to access public directory, ${status}`); 122 } 123 }; 124 // Start to copy files cross devices. 125 fs.connectDfs(networkId, listeners).then(()=>{ 126 try { 127 // Copy the file in the distributed file directory to the destination sandbox directory. 128 fs.copy(srcUri, destUri, options).then(()=>{ 129 console.info(`Succeeded in copying from distribted path`); 130 console.info(`src: ${srcUri} dest: ${destUri}`); 131 fs.unlinkSync(srcPath); // Remove the temporary file in the distributed file directory after the copy is complete. 132 }).catch((error: BusinessError)=>{ 133 let err: BusinessError = error as BusinessError; 134 console.error(`Failed to copy. Code: ${err.code}, message: ${err.message}`); 135 }) 136 } catch (error) { 137 console.error(`Catch err. Failed to copy. Code: ${error.code}, message: ${error.message}`); 138 } 139 }).catch((error: BusinessError) => { 140 let err: BusinessError = error as BusinessError; 141 console.error(`Failed to connect dfs. Code: ${err.code}, message: ${err.message}`); 142 }); 143 } 144 ``` 145 1464. Disconnect the link for device B. 147 148 ```ts 149 import { BusinessError } from '@kit.BasicServicesKit'; 150 import { distributedDeviceManager } from '@kit.DistributedServiceKit' 151 import { fileIo as fs } from '@kit.CoreFileKit'; 152 153 // Obtain the network ID of device A. 154 let dmInstance = distributedDeviceManager.createDeviceManager("com.example.hap"); 155 let deviceInfoList: Array<distributedDeviceManager.DeviceBasicInfo> = dmInstance.getAvailableDeviceListSync(); 156 if (deviceInfoList && deviceInfoList.length > 0) { 157 console.info(`Success to get available device list`); 158 let networkId = deviceInfoList[0].networkId; // Only two devices are connected. The first element in the list is the network ID of device A. 159 // Disable cross-device file copy. 160 fs.disconnectDfs(networkId).then(() => { 161 console.info(`Success to disconnect dfs`); 162 }).catch((error: BusinessError) => { 163 let err: BusinessError = error as BusinessError; 164 console.error(`Failed to disconnect dfs. Code: ${err.code}, message: ${err.message}`); 165 }) 166 } 167 ``` 168