forked from Gitlink/forgeplus-react
78 lines
2.2 KiB
JavaScript
78 lines
2.2 KiB
JavaScript
import React, { useEffect , useState } from "react";
|
|
import { Upload } from 'antd';
|
|
import { getUploadActionUrl, appendFileSizeToUploadFileAll } from 'educoder';
|
|
|
|
import axios from 'axios';
|
|
|
|
function Single({ children , showNotification , className , load , size }) {
|
|
const [ fileList , setFileList ] = useState(undefined);
|
|
// 移除
|
|
function onAttachmentRemove(file){
|
|
if (!file.percent || file.percent === 100) {
|
|
deleteAttachment(file);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
function deleteAttachment(file){
|
|
let uid = file.response ? file.response.id : file.uid;
|
|
const url = `/attachments/${uid}.json`
|
|
axios.delete(url).then((response) => {
|
|
if (response.data && response.data.status === 0) {
|
|
let list = fileList.filter(item=> item.response && item.response.id !== uid);
|
|
setFileList(list);
|
|
fileIdList(list);
|
|
}
|
|
}).catch(error=>{});
|
|
}
|
|
|
|
|
|
function handleChange(info){
|
|
if (info.file.status === 'uploading' || info.file.status === 'done' || info.file.status === 'removed') {
|
|
let fileList = [info.file];
|
|
|
|
let list = appendFileSizeToUploadFileAll(fileList);
|
|
setFileList(list);
|
|
if ( info.file.status === 'done') {
|
|
let f = info.fileList && info.fileList.length>0 && info.fileList[info.fileList.length-1];
|
|
if(f && f.response && f.response.status === -1){
|
|
showNotification(f.response.message)
|
|
setFileList(f);
|
|
}
|
|
fileIdList(fileList);
|
|
}
|
|
}
|
|
}
|
|
|
|
function fileIdList(fileList){
|
|
let l = fileList && fileList.length > 0 && fileList[0];
|
|
let array = [l && l.response && l.response.id];
|
|
load && load(array);
|
|
}
|
|
|
|
function beforeUpload(file){
|
|
if(!size) return;
|
|
const isLt100M = file.size / 1024 / 1024 < size;
|
|
if (!isLt100M) {
|
|
showNotification(`文件大小必须小于${size}MB!`);
|
|
}
|
|
return isLt100M;
|
|
}
|
|
|
|
//判断是否已经提交,如已提交评论则上一条评论数据清除
|
|
const upload = {
|
|
name: 'file',
|
|
fileList: fileList,
|
|
action: `${getUploadActionUrl()}`,
|
|
onChange: handleChange,
|
|
onRemove: onAttachmentRemove,
|
|
beforeUpload: beforeUpload
|
|
};
|
|
|
|
return (
|
|
<Upload {...upload} className={className}>
|
|
{children}
|
|
</Upload>
|
|
)
|
|
}
|
|
export default Single; |