react native实现文件下载、编辑、上传功能

插件:react-native-fs

GitHub链接:https://github.com/itinance/react-native-fs#readme

实现:

  1. 文件下载保存到本地
  2. 读取、编辑文件
  3. 上传文件
  4. 删除文件

API参考:

pathAPI

```JavaScript
MainBundlePath (String) 主包目录的绝对路径(在 Android 上不可用)
CachesDirectoryPath (String) 缓存目录的绝对路径
ExternalCachesDirectoryPath (String) 外部缓存目录的绝对路径(仅限安卓)
DocumentDirectoryPath (String) 文档目录的绝对路径
DownloadDirectoryPath (String) 下载目录的绝对路径(仅在 android 上)
TemporaryDirectoryPath (String) 临时目录的绝对路径(在 Android 上回退到 Caching-Directory)
LibraryDirectoryPath (String) NSLibraryDirectory 的绝对路径(仅限 iOS)
ExternalDirectoryPath (String) 外部文件的绝对路径,共享目录(仅限安卓)
ExternalStorageDirectoryPath (String) 外部存储的绝对路径,共享目录(仅限安卓)
```

downloadAPI

```JavaScript
fromUrl:字符串; // 下载文件的 URL
toFile: 字符串; // 将文件保存到的本地文件系统路径
headers?:标题; // 要传递给服务器的标头对象
background?:布尔值; // 应用终止后继续在后台下载(仅限iOS)
discretionary?:布尔值; // 允许操作系统控制下载的时间和速度以提高感知性能(仅限 iOS)
cacheable?:布尔值; // 下载是否可以存储在共享的NSURLCache中(仅限iOS,默认为true)
progressInterval?:数字;
progressDivider?:数字;
begin?:(res:DownloadBeginCallbackResult)=> void;
progress?:(res:DownloadProgressCallbackResult)=> void;
resumable?:()=> void; // 目前只支持 iOS
connectionTimeout?: number // 目前仅在 Android 上支持
readTimeout?: number // Android 和 iOS 支持
backgroundTimeout?: number // 下载整个资源的最长时间(以毫秒为单位)(仅限 iOS,用于后台下载超时)
```

使用:

util.ts

import RNFS from 'react-native-fs';

// 传入一个url和名字,下载到指定目录
export const downloadTxt = (path:string,name:string)=>{
    const installUrl = path;
    const filePath = RNFS.ExternalCachesDirectoryPath + `/${name}.txt`
    const download = RNFS.downloadFile({
        fromUrl: installUrl,
        toFile: filePath,
    })
    return download.promise
}

// 创建一个txt
export const createTxt = (name:string,content:string)=>{
    const filePath = RNFS.ExternalCachesDirectoryPath + `/${name}.txt`
    return RNFS.writeFile(path, content, 'utf8')
}

// 读取一个txt的内容
export const createTxt = (name:string)=>{
    const filePath = RNFS.ExternalCachesDirectoryPath + `/${name}.txt`
    return RNFS.readFile(path)
}

// 编辑一个txt的内容
export const appendTxt = (name:string,content:string)=>{
    const filePath = RNFS.ExternalCachesDirectoryPath + `/${name}.txt`
    return RNFS. appendFile(path, content, 'utf8')
}

// 删除这个文件所在的文件夹(Linux rm -rf)
export const deleteTxt = ()=>{
    if (RNFS.exists(RNFS.ExternalCachesDirectoryPath)) {
        RNFS.unlink(RNFS.ExternalCachesDirectoryPath)
        // RNFS.unlink(RNFS.ExternalCachesDirectoryPath+`/${name}.txt`)
        // 也可指定文件删除
    }
}

index.tsx

import React, { useState, useEffect } from 'react';
import RNFS from 'react-native-fs';
import { Button, Toast } from 'react-native'
import { downloadTxt, appendTxt, deleteTxt } from './util.ts';

const fileName = 'test';
const demo = () => {
    const [ isdownload, setIsdownload ] = useState<boolean>(false);
    
    useEffect(()=>{
        return ()=>{
            deleteTxt()
            // 界面销毁删除文件夹也可以修改函数实现不删除文件夹
        }
    })

    const handleDownloadTxt = () => {
        const installUrl = 'http://localhost:8080/test.txt'; // 网络文件
        // 这里使用localhost是通过node起了一个服务做静态代理等同于读取到一个网络文件
        downloadTxt(installUrl,fileName).then(result=>{
            if (result.statusCode === 200) {
                console.log('file://' + RNFS.ExternalCachesDirectoryPath + fileName + '.txt')
                setIsdownload(true)
            }
        })
    }

    const handleAppendTxt = () =>{
        if(!isdownload) return Toast.fail('未下载')
        appendTxt(fileName,'编辑了这个文件').then(result=>{
             console.log('success');
        })
    }

    const handleuploadTxt = () => {
        const filePath = 'file://' + RNFS.ExternalCachesDirectoryPath + 
fileName +'.txt';
        // 已经获取到文件路径了,通过指定的方法把这个文件上传到相应的服务器就行了
    }

    return (
        <>
            <Button onPress={handleDownloadTxt}>下载txt</Button>
            <Button onPress={handleAppendTxt}>编辑下载好的txt</Button>
            <Button onPress={handleuploadTxt}>上传txt</Button>
        </>
    )
    
}

export default demo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值