import React, {
useState,
useCallback,
useEffect,
} from 'react';
import {useDropzone} from 'react-dropzone';
import "./dropzone.styles.css"
import InfiniteScroll from 'react-infinite-scroller';
import {
List,
message,
// Avatar,
Spin,
} from 'antd';
import axios from 'axios';
/**
* 计算文件大小
* @param {*} bytes
* @param {*} decimals
* @returns
*/
function formatBytes(bytes, decimals = 2) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const dm = decimals < 0 ? 0 : decimals;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}
/**
* Dropzone 上传文件
* @param {*} props
* @returns
*/
function DropzoneUpload(props) {
const [files, setFiles] = useState([])
const [loading, setLoading] = useState(false);
const [hasMore, setHasMore] = useState(true);
const onDrop = useCallback(acceptedFiles => {
setLoading(true);
const formData = new FormData();
smallFiles.forEach(file => {
formData.append("files", file);
});
axios({
method: 'POST',
url: '/api/files/multiplefiles',
data: formData,
headers: {
"Content-Type": "multipart/form-data",
}
})
then(resp => {
addFiles(acceptedFiles);
setLoading(false);
});
}, [files]);
// Dropzone setting
const { getRootProps, getInputProps } = useDropzone({
multiple:true,
onDrop,
});
// 删除附件
const removeFile = file => {
const newFiles = [...files]
newFiles.splice(newFiles.indexOf(file), 1)
setFiles(newFiles)
}
useEffect(() => {
// init uploader files
setFiles([])
},[])
return (
<section className="container">
<div {...getRootProps({className: 'dropzone'})}>
<input {...getInputProps()} />
<p>拖动文件或点击选择文件😊</p>
</div>
<div className="demo-infinite-container">
<InfiniteScroll
initialLoad={false}
pageStart={0}
loadMore={handleInfiniteOnLoad}
hasMore={!loading && hasMore}
useWindow= {false}
>
<List
dataSource={files}
renderItem={item=> (
<List.Item
actions={[
// <a key="list-loadmore-edit">编辑</a>,
<a key="list-loadmore-delete" onClick={removeFile}>删除</a>
]}
// extra={
// }
key={item.path}>
<List.Item.Meta
avatar={
<>
{
!!item.type && ['image/gif', 'image/jpeg', 'image/png'].includes(item.type) &&
<img
width={100}
alt='logo'
src={item.preview}
/>
}
</>
}
title={item.path}
description={formatBytes(item.size)}
/>
</List.Item>
)}
>
{loading && hasMore && (
<div className="demo-loading-container">
<Spin />
</div>
)}
</List>
</InfiniteScroll>
</div>
</section>
);
}
评论