FilesTable.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. import React, { useEffect, useState } from 'react';
  2. import {
  3. Button,
  4. Form,
  5. Header,
  6. Icon,
  7. Pagination,
  8. Popup,
  9. Progress,
  10. Segment,
  11. Table,
  12. } from 'semantic-ui-react';
  13. import { API, copy, showError, showSuccess } from '../helpers';
  14. import { useDropzone } from 'react-dropzone';
  15. import { ITEMS_PER_PAGE } from '../constants';
  16. const FilesTable = () => {
  17. const [files, setFiles] = useState([]);
  18. const [loading, setLoading] = useState(true);
  19. const [activePage, setActivePage] = useState(1);
  20. const [searchKeyword, setSearchKeyword] = useState('');
  21. const [searching, setSearching] = useState(false);
  22. const { acceptedFiles, getRootProps, getInputProps } = useDropzone();
  23. const [uploading, setUploading] = useState(false);
  24. const [uploadProgress, setUploadProgress] = useState('0');
  25. const loadFiles = async (startIdx) => {
  26. const res = await API.get(`/api/file/?p=${startIdx}`);
  27. const { success, message, data } = res.data;
  28. if (success) {
  29. if (startIdx === 0) {
  30. setFiles(data);
  31. } else {
  32. let newFiles = files;
  33. newFiles.push(...data);
  34. setFiles(newFiles);
  35. }
  36. } else {
  37. showError(message);
  38. }
  39. setLoading(false);
  40. };
  41. const onPaginationChange = (e, { activePage }) => {
  42. (async () => {
  43. if (activePage === Math.ceil(files.length / ITEMS_PER_PAGE) + 1) {
  44. // In this case we have to load more data and then append them.
  45. await loadFiles(activePage - 1);
  46. }
  47. setActivePage(activePage);
  48. })();
  49. };
  50. useEffect(() => {
  51. loadFiles(0)
  52. .then()
  53. .catch((reason) => {
  54. showError(reason);
  55. });
  56. }, []);
  57. const downloadFile = (link, filename) => {
  58. let linkElement = document.createElement('a');
  59. linkElement.download = filename;
  60. linkElement.href = '/upload/' + link;
  61. linkElement.click();
  62. };
  63. const copyLink = (link) => {
  64. let url = window.location.origin + '/upload/' + link;
  65. copy(url).then();
  66. showSuccess('链接已复制到剪贴板');
  67. };
  68. const deleteFile = async (id, idx) => {
  69. const res = await API.delete(`/api/file/${id}`);
  70. const { success, message } = res.data;
  71. if (success) {
  72. let newFiles = [...files];
  73. let realIdx = (activePage - 1) * ITEMS_PER_PAGE + idx;
  74. newFiles[realIdx].deleted = true;
  75. // newFiles.splice(idx, 1);
  76. setFiles(newFiles);
  77. showSuccess('文件已删除!');
  78. } else {
  79. showError(message);
  80. }
  81. };
  82. const searchFiles = async () => {
  83. if (searchKeyword === '') {
  84. // if keyword is blank, load files instead.
  85. await loadFiles(0);
  86. setActivePage(1);
  87. return;
  88. }
  89. setSearching(true);
  90. const res = await API.get(`/api/file/search?keyword=${searchKeyword}`);
  91. const { success, message, data } = res.data;
  92. if (success) {
  93. setFiles(data);
  94. setActivePage(1);
  95. } else {
  96. showError(message);
  97. }
  98. setSearching(false);
  99. };
  100. const handleKeywordChange = async (e, { value }) => {
  101. setSearchKeyword(value.trim());
  102. };
  103. const sortFile = (key) => {
  104. if (files.length === 0) return;
  105. setLoading(true);
  106. let sortedUsers = [...files];
  107. sortedUsers.sort((a, b) => {
  108. return ('' + a[key]).localeCompare(b[key]);
  109. });
  110. if (sortedUsers[0].id === files[0].id) {
  111. sortedUsers.reverse();
  112. }
  113. setFiles(sortedUsers);
  114. setLoading(false);
  115. };
  116. const uploadFiles = async () => {
  117. if (acceptedFiles.length === 0) return;
  118. setUploading(true);
  119. let formData = new FormData();
  120. for (let i = 0; i < acceptedFiles.length; i++) {
  121. formData.append('file', acceptedFiles[i]);
  122. }
  123. const res = await API.post(`/api/file`, formData, {
  124. headers: {
  125. 'Content-Type': 'multipart/form-data',
  126. },
  127. onUploadProgress: (e) => {
  128. let uploadProgress = ((e.loaded / e.total) * 100).toFixed(2);
  129. setUploadProgress(uploadProgress);
  130. },
  131. });
  132. const { success, message } = res.data;
  133. if (success) {
  134. showSuccess(`${acceptedFiles.length} 个文件上传成功!`);
  135. } else {
  136. showError(message);
  137. }
  138. setUploading(false);
  139. setUploadProgress('0');
  140. setSearchKeyword('');
  141. loadFiles(0).then();
  142. setActivePage(1);
  143. };
  144. useEffect(() => {
  145. uploadFiles().then();
  146. }, [acceptedFiles]);
  147. return (
  148. <>
  149. <Segment
  150. placeholder
  151. {...getRootProps({ className: 'dropzone' })}
  152. loading={uploading || loading}
  153. style={{ cursor: 'pointer' }}
  154. >
  155. <Header icon>
  156. <Icon name='file outline' />
  157. 拖拽上传或点击上传
  158. <input {...getInputProps()} />
  159. </Header>
  160. </Segment>
  161. {uploading ? (
  162. <Progress
  163. percent={uploadProgress}
  164. success
  165. progress='percent'
  166. ></Progress>
  167. ) : (
  168. <></>
  169. )}
  170. <Form onSubmit={searchFiles}>
  171. <Form.Input
  172. icon='search'
  173. fluid
  174. iconPosition='left'
  175. placeholder='搜索文件的名称,上传者以及描述信息 ...'
  176. value={searchKeyword}
  177. loading={searching}
  178. onChange={handleKeywordChange}
  179. />
  180. </Form>
  181. <Table basic>
  182. <Table.Header>
  183. <Table.Row>
  184. <Table.HeaderCell
  185. style={{ cursor: 'pointer' }}
  186. onClick={() => {
  187. sortFile('filename');
  188. }}
  189. >
  190. 文件名
  191. </Table.HeaderCell>
  192. <Table.HeaderCell
  193. style={{ cursor: 'pointer' }}
  194. onClick={() => {
  195. sortFile('uploader_id');
  196. }}
  197. >
  198. 上传者
  199. </Table.HeaderCell>
  200. <Table.HeaderCell
  201. style={{ cursor: 'pointer' }}
  202. onClick={() => {
  203. sortFile('email');
  204. }}
  205. >
  206. 上传时间
  207. </Table.HeaderCell>
  208. <Table.HeaderCell>操作</Table.HeaderCell>
  209. </Table.Row>
  210. </Table.Header>
  211. <Table.Body>
  212. {files
  213. .slice(
  214. (activePage - 1) * ITEMS_PER_PAGE,
  215. activePage * ITEMS_PER_PAGE
  216. )
  217. .map((file, idx) => {
  218. if (file.deleted) return <></>;
  219. return (
  220. <Table.Row key={file.id}>
  221. <Table.Cell>
  222. <a href={'/upload/' + file.link} target='_blank'>
  223. {file.filename}
  224. </a>
  225. </Table.Cell>
  226. <Popup
  227. content={'上传者 ID:' + file.uploader_id}
  228. trigger={<Table.Cell>{file.uploader}</Table.Cell>}
  229. />
  230. <Table.Cell>{file.upload_time}</Table.Cell>
  231. <Table.Cell>
  232. <div>
  233. <Button
  234. size={'small'}
  235. positive
  236. onClick={() => {
  237. downloadFile(file.link, file.filename);
  238. }}
  239. >
  240. 下载
  241. </Button>
  242. <Button
  243. size={'small'}
  244. negative
  245. onClick={() => {
  246. deleteFile(file.id, idx).then();
  247. }}
  248. >
  249. 删除
  250. </Button>
  251. <Button
  252. size={'small'}
  253. onClick={() => {
  254. copyLink(file.link);
  255. }}
  256. >
  257. 复制链接
  258. </Button>
  259. </div>
  260. </Table.Cell>
  261. </Table.Row>
  262. );
  263. })}
  264. </Table.Body>
  265. <Table.Footer>
  266. <Table.Row>
  267. <Table.HeaderCell colSpan='6'>
  268. <Pagination
  269. floated='right'
  270. activePage={activePage}
  271. onPageChange={onPaginationChange}
  272. size='small'
  273. siblingRange={1}
  274. totalPages={
  275. Math.ceil(files.length / ITEMS_PER_PAGE) +
  276. (files.length % ITEMS_PER_PAGE === 0 ? 1 : 0)
  277. }
  278. />
  279. </Table.HeaderCell>
  280. </Table.Row>
  281. </Table.Footer>
  282. </Table>
  283. </>
  284. );
  285. };
  286. export default FilesTable;