Skip to content

Commit

Permalink
feat(usefile): add useFile hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
innocces committed Aug 13, 2021
1 parent 4abce7d commit 774458a
Show file tree
Hide file tree
Showing 9 changed files with 199 additions and 1 deletion.
19 changes: 19 additions & 0 deletions .licrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
[licenses]
# This indicates which are the only licenses that Licensebat will accept.
# The rest will be flagged as not allowed.
accepted = ["MIT", "MSC", "BSD", "Apache"]
# This will indicate which licenses are not accepted.
# The rest will be accepted, except for the unknown licenses or dependencies without licenses.
# unaccepted = ["LGPL"]
# Note that only one of the previous options can be enabled at once.
# If both of them are informed, only accepted will be considered.

[dependencies]
# This will allow users to flag some dependencies so that Licensebat will not check for their license.
ignored=["@taro/tarojs", "react", "react-dom"]

[behavior]
# False by default, if true, it will only run the checks when one of the dependency files or the .licrc file has been modified.
run_only_on_dependency_modification = true
# False by default, if true, it will never block the build.
do_not_block_pr = false
1 change: 1 addition & 0 deletions packages/app/src/app.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export default {
'pages/useRequest/loadMoreRef/index',
'pages/useNetworkType/index',
'pages/useOnline/index',
'pages/useFile/index',
// device
'pages/useBattery/index',
'pages/useVibrate/index',
Expand Down
4 changes: 4 additions & 0 deletions packages/app/src/constant/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,10 @@ export const ChildrenList: { [_: string]: APIChildrenItem[] } = {
id: 'useOnline',
name: 'useOnline 网络状态',
},
{
id: 'useFile',
name: 'useFile 上传下载',
},
],
};

Expand Down
3 changes: 3 additions & 0 deletions packages/app/src/pages/useFile/index.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default {
navigationBarTitleText: 'useFile',
};
62 changes: 62 additions & 0 deletions packages/app/src/pages/useFile/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import React, { useCallback } from 'react';
import { AtButton } from 'taro-ui';

import DocPage from '@components/DocPage';

import { useFile, useImage, useModal } from 'taro-hooks';

export default () => {
const { download, upload } = useFile();
const [, { choose, preview }] = useImage({});
const [showModal] = useModal({ mask: true, title: '文件结果' });

const handleUpload = useCallback(async () => {
const fileInfo = await choose();
if (fileInfo?.tempFilePaths?.length) {
const uploadFilePath = fileInfo.tempFilePaths[0];
const uploadResult = await upload({
url: 'https://run.mocky.io/v3/35b34abe-3f7e-4cde-91a8-da02f699bdc0',
filePath: uploadFilePath,
name: 'chooseImage:file',
header: {},
});
const modalContent =
uploadResult?.statusCode === 200 ? uploadResult?.data : '上传失败';
showModal({ content: modalContent });
} else {
showModal({
content: '取消选择',
});
}
}, [choose, upload, showModal]);

const handleDownload = useCallback(async () => {
try {
const result = await download({
url: 'https://pixabay.com/get/gca7a9aedd24075bee51ccdc9e510d6d78d66b2b607c643e63260d944732a75301e6ce92f56e371d0ea11c55613742929_640.jpg',
});
if (result.statusCode === 200 && result?.tempFilePath) {
preview({
urls: [result?.tempFilePath],
});
} else {
throw new Error();
}
} catch (e) {
showModal({
content: 'downloadFile: fail',
});
}
}, [download, showModal, preview]);

return (
<>
<DocPage title="useFile 上传下载" panelTitle="useFile">
<AtButton onClick={handleUpload}>选择图片上传</AtButton>
<AtButton className="gap" onClick={handleDownload}>
下载图片
</AtButton>
</DocPage>
</>
);
};
2 changes: 2 additions & 0 deletions packages/hooks/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import useUpdateManager from './useUpdateManager';
import useNetworkType from './useNetworkType';
import useOnline from './useOnline';
import useRequest from './useRequest';
import useFile from './useFile';

// device
import useBattery from './useBattery';
Expand Down Expand Up @@ -62,6 +63,7 @@ export {
useNetworkType,
useOnline,
useRequest,
useFile,
useToast,
useModal,
useLoading,
Expand Down
40 changes: 40 additions & 0 deletions packages/hooks/src/useFile/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
---
title: useFile
nav:
title: Hooks
path: /hooks
order: 2
group:
title: 网络
path: /network
---

# useFile

上传、下载文件

## 何时使用

当需要上传下载文件时

## API

```jsx | pure
const visible: boolean = useVisible();
```

## 返回值说明

| 返回值 | 说明 | 类型 |
| ------- | -------------------- | --------- |
| visible | 当前应用是否处于后台 | `boolean` |

## 代码演示

<code src="@pages/useFile" />

## Hook 支持度

| 微信小程序 | H5 | ReactNative |
| :--------: | :-: | :---------: |
| ✔️ | ✔️ | |
68 changes: 68 additions & 0 deletions packages/hooks/src/useFile/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { uploadFile, downloadFile, General } from '@tarojs/taro';
import { useCallback } from 'react';

export interface IUploadOption {
url: string;
filePath: string;
name: string;
header?: Record<string, any>;
formData?: Record<string, any>;
timeout?: number;
fileName?: string;
}

export interface IDownloadOption {
url: string;
filePath?: string;
header?: Record<string, any>;
}

export type IUploadFileAction = (
option: IUploadOption,
) => Promise<uploadFile.SuccessCallbackResult | General.CallbackResult>;

export type IDownloadFileAction = (
option: IDownloadOption,
) => Promise<downloadFile.FileSuccessCallbackResult | General.CallbackResult>;

export interface IAction {
upload: IUploadFileAction;
download: IDownloadFileAction;
}

function useFile(): IAction {
const upload = useCallback<IUploadFileAction>((option) => {
return new Promise((resolve, reject) => {
try {
uploadFile({
...(option || {}),
success: resolve,
fail: reject,
}).catch(reject);
} catch (e) {
reject({ errMsg: 'uploadFile:fail' });
}
});
}, []);

const download = useCallback<IDownloadFileAction>((option) => {
return new Promise((resolve, reject) => {
try {
downloadFile({
...(option || {}),
success: resolve,
fail: reject,
});
} catch (e) {
reject({ errMsg: 'downloadFile:fail' });
}
});
}, []);

return {
upload,
download,
};
}

export default useFile;
1 change: 0 additions & 1 deletion packages/hooks/src/useImage/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@ function useImage(options: ChooseImageOption): [IFileInfo, IAction] {
chooseImage({
...finalOptions,
success: (res) => {
console.log(res);
const { errMsg, ...fileInfo } = res;
setFileInfo(fileInfo);
resolve(res);
Expand Down

2 comments on commit 774458a

@vercel
Copy link

@vercel vercel bot commented on 774458a Aug 13, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

taro-hooks – ./

taro-hooks.vercel.app
taro-hooks-ff-docs.vercel.app
taro-hooks-git-main-ff-docs.vercel.app

@vercel
Copy link

@vercel vercel bot commented on 774458a Aug 13, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

taro-hooks-h5 – ./

taro-hooks-h5-ff-docs.vercel.app
taro-hooks-h5.vercel.app
taro-hooks-h5-git-main-ff-docs.vercel.app

Please # to comment.